Friday, March 26, 2010

Everything fits IN a NULL

I just learned something I hadn't really thought about before: while a NULL is nothing, everything is IN a NULL. What I mean is when doing a comparison of ...


WHERE a.something IN (SELECT things FROM aTable)


...if any of the values in your target collection are NULL, the IN comparison will return true, even if the source is not NULL.

To get around this, my co-worker came up with a quick and clever solution:


WHERE a.something IN (SELECT ISNULL(things,-1) FROM aTable)


This simply removes any NULLs from the target collection without having to do a NULL comparison on the source value. Obviously, the alternate value in your ISNULL() function would have to be something that cannot be your source value, so -1 may not be the correct value for your query, but you get the idea....it's important to know if there are any NULL values in the target collection, because aparently the IN function will say that pretty much anything is in a NULL value.