0

I recently uncovered a query (which has since been lost) that seemed to have an issue stemming from the use of a subquery alongside an IN clause. For example:

SELECT * FROM Table1 WHERE Column1 IN (SELECT Column1 FROM Table2)

The issue I seemed to notice was that when I used IN and NOT IN, the figures with each did not account for the total records in Table1. Whilst Table1 did not have any NULL values in Column1, I believe that Table2 did. Could this have caused an issue? I appreciate that comparing something to NULL via the standard logical operators will not work in T-SQL, but I have not been able to find anything regarding IN clauses with subqueries.

I unfortunately do not have the original query, and when I tried to reproduce the issue using some very general code, I could not. So I appreciate this is perhaps a vague question, but it would be useful to know of any 'dangers' that people may not be generally aware of when using the IN/NOT IN operators with a subquery, specifically relating to NULLS. Any other general dangers not necessarily relating to NULLS would also be useful.

I would assume the general advice would be to use a JOIN, however this is primarily so that I can identify possible issues in existing code and remediate if necessary.

1

1 Answer 1

0

The following query:

SELECT *
FROM Table1
WHERE Column1 NOT IN (SELECT Column1 FROM Table2)

Will never return any rows if Table2.Column1 is ever NULL. Why? Well, if Column1 matches a value in Table2, then the expression returns false. If Column1 does not match a value, then you have the comparison to NULL -- and that comparison returns NULL.

My advice is to use NOT EXISTS instead:

SELECT t1.*
FROM Table1 t1
WHERE NOT EXISTS (SELECT Column1 FROM Table2 t2 WHERE t2.Column1 = t1.Column1)

This has the more expected behavior.

You can use JOIN, but that runs the risk of producing duplicate rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.