I have a bit column on a table in a SQL Server 2012 database.
I am trying to retrieve all the rows where this bit column is either NULL or NOT TRUE.
This query does not bring back what it should: (returns 0 rows)
Select *
from table
where bit_column_value <> 1
This query brings back the correct rows:
Select *
from table
where bit_column_value IS NULL
Now, I’d be happy to use the second query, but my issue is that, in a similar query for another table, the reverse of the above is true, where the first way works, but the second way does not!
Could someone assist in explaining what the difference is in the above? I have specifically updated the relevant bit columns to be NULL and this does not change the results. (Thought maybe there was a difference between “Empty” and Null values.
Thanks in advance for any explanations.
The reason
<>doesn’t work is that SQL treatsNULLas unknown – it doesn’t know whatNULLis supposed to mean, so it evaluates both=and<>on aNULLvalue asUNKNOWN(which is treated as false in a where clause or join condition). For more info, read this: Why does NULL = NULL evaluate to false in SQL server.If there’s an index on it, using the ISNULL function will mean the index can’t be used, so to
ensure the query can use the index just use
OR: