Saturday, February 7, 2015

SQL: Querying NULL Records in SQL Server

As a developer we always forget how to query for records with NULL values, no matter how many times we do it. It's just weird. Our first instinct is to write the query as such

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region = NULL
But that will not return any results. The funny thing is there's no SQL error so you think that there's no results. However if you change the query to this

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NULL
You see there's plenty of records with Region IS NULL

The reverse is true if you want records that are not NULL you would not write the query like this

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region != NULL
But you want to write the query like this instead

SELECT CompanyName, ContactName, ContactTitle,Region
FROM Customers
WHERE Region IS NOT NULL


No comments:

Post a Comment