Question

Can any one explain to me why I'm getting different results:

Table2.Table1ID nullable field

SELECT * FROM Table1
WHERE
ID NOT IN (SELECT Table1ID FROM Table2)

no results

SELECT * FROM Table1
WHERE
ID NOT IN (SELECT Table1ID FROM Table2 WHERE Table1ID IS NOT NULL)

expected results: Table1 items which are not related to Table2

SQL server version: 10.50.3720.0 OS: Microsoft Windows NT 6.1 (7601)

Was it helpful?

Solution

If any of the values in the Table2 has null then First query gets transalted to

SELECT * FROM Table1
WHERE (ID <> NULL and ID <> SomeValue and...)

ID<>NULL is unkown .Hence you don't get any result

where as, in your 2nd query you are eliminating the NULL .Hence you don't get an unknown value .

You can also write your query using Not Exists

SELECT * FROM Table1
WHERE
NOT Exists (SELECT 1  FROM Table2 where Table1ID = ID )

OTHER TIPS

SELECT * FROM Table1
WHERE
ID NOT IN (SELECT ISNULL(Table1ID, ' ') FROM Table2)

NOT IN with NULL will end up in failing all condition! It is same with oracle as well!

NOT IN... NULL obviousy is hypothetical!.. Not in nothing, literally even is a not a valid one isn't it!

NULL is something, like not defined.. So we have special functions available to handle NULL. Even for comparison we use IS NULL and Not = NULL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top