SQL "NOT IN" Will Fail If The List Contains A Null

If you are using the NOT IN clause with a SQL Select statement with SQL Server it will not work if there is a null value in the list.  Say for example you want to do:

SELECT * FROM
Employees
Where
Employee.Id NOT IN
(
   Select EmployeeId from
   Salaries
   where Salary < 100000
)

If the inner select returns a null value then the outer select statement will return no rows.

To try it, just run these 2 SQL statments against any table in your DB.

-- will return rows
SELECT * FROM
sometable
WHERE ID NOT IN (1,2,3)

-- will return nothing
SELECT * FROM
sometable
WHERE ID NOT IN (1,2,3, null)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s