Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL And NULL Values in where clause

So I have a simple query that returns a listing of products

SELECT     Model, CategoryID
FROM         Products
WHERE     (Model = '010-00749-01') 

This returns

010-00749-01    00000000-0000-0000-0000-000000000000
010-00749-01    NULL

Which is correct, so I wanted only the products whose CategoryID is not '00000000-0000-0000-0000-000000000000' so I have

SELECT     Model, CategoryID
FROM         Products
WHERE     (Model = '010-00749-01') 
AND (CategoryID <> '00000000-0000-0000-0000-000000000000') 

But this returns no result. So I changed the query to

SELECT     Model, CategoryID
FROM         Products
WHERE     (Model = '010-00749-01') 
AND ((CategoryID <> '00000000-0000-0000-0000-000000000000') OR  (CategoryID  IS NULL))

Which returns expected result

010-00749-01    NULL

Can someone explain this behavior to me? MS SQL Server 2008

like image 291
Greg Avatar asked Oct 14 '10 21:10

Greg


People also ask

WHERE condition in SQL is NULL and value?

What is a NULL Value? A field with a NULL value is a field with no value. If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.

Is NULL in WHERE clause SQL Server?

Let's look at how to use the IS NULL condition in a SELECT statement in SQL Server. For example: SELECT * FROM employees WHERE last_name IS NULL; This SQL Server IS NULL example will return all records from the employees table where the last_name contains a null value.

Is NULL in mysql in WHERE clause?

To test for NULL in a query, you use the IS NULL or IS NOT NULL operator in the WHERE clause. You can use the IS NOT operator to get all leads who provided the email addresses. Even though the NULL is not equal to NULL , two NULL values are equal in the GROUP BY clause.

How do you deal with NULL values in SQL?

Handling SQL NULL values with Functions ISNULL(): The ISNULL() function takes two parameters and it enables us to replace NULL values with a specified value. The expression parameter indicates the expression which we want to check NULL values.


1 Answers

Basically, a NULL is the absence of any value. So trying to compare the NULL in CategoryId to a varchar value in the query will always result in a false evaluation.

You might want to try using the COALESCE function, something like:

SELECT     ModelId, CategoryID 
FROM       Products 
WHERE      (ModelId = '010-00749-01')  
AND        ( COALESCE( CategoryID, '' ) <> '00000000-0000-0000-0000-000000000000' ) 

EDIT

As noted by AdaTheDev the COALESCE function will negate any indices that may exist on the CategoryID column, which can affect the query plan and performance.

like image 105
Bob Mc Avatar answered Sep 20 '22 01:09

Bob Mc