These are rather basic statements. I have a list of graphics which are linked to items in another table. I want to check how many of the graphics are not in use and can theoreti
That because of NULL
value returned from subquery
:
SELECT [GraphicNr], [Graphicfile]
FROM [dbo].[Graphic]
WHERE graphicnr NOT IN (SELECT graphicnr FROM dbo.Komp)
This would produce no records
or no rows affected
because of graphicnr not in (null)
which is not desired output.
So, the NOT EXISTS
would not work as the way the IN
clause or NOT IN
work. It behaves differently then IN
or NOT IN
clause.
However, you can prevent this by using IS NOT NULL
filter in subquery
. But the recommended way is to use NOT EXISTS
instead.
NOT IN
with a subquery has strange behavior. If any row in the subquery returns a NULL
value, then no rows are returned. This is due to following the strict semantics of NULL
(which means: "I don't know if they are equal").
NOT EXISTS
behaves as you would expect. For this reason, I recommend never using NOT IN
with a subquery. Always use NOT EXISTS
.