Sorry guys, I had no idea how to phrase this one, but I have the following in a where clause:
person_id not in (
SELECT distinct person_id
FROM protocol_application_log_devl pal
WHERE pal.set_id = @set_id
)
When the subquery returns no results, my whole select fails to return anything. To work around this, I replaced person_id
in the subquery with isnull(person_id, '00000000-0000-0000-0000-000000000000')
.
It seems to work, but is there a better way to solve this?
It is better to use
NOT EXISTS
anyway:Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
While I support Tim's answer as being correct-in-practice (NOT IN is not appropriate here), this is an interesting case noted in the IN / NOT IN documentation:
This is why the
isnull
"fixes" the problem - it masks any such NULL values and avoids the unexpected behavior. With that in mind, the following approach would also work (but please heed the advice about not using NOT IN to begin with):However, a NULL person_id is suspicious and might indicate other issues ..
1 Here is the Proof pudding: