I have a table with 200 records out of which 10 records has text containing the word 'TAX'.
When I'm executing
Select * from tbl1 WHERE [TextCol] LIKE '%TAX%'
then I get the result set with those 10 records correctly .
But when I am trying to exclude those records by
Select * from tbl1 WHERE [TextCol] NOT LIKE '%TAX%'
it's returning 100 records only, instead of 190.
(A) SQL comparison operators result in three possible values: True, False and Unknown. If one or both operands are
NULL
then the result is Unknown. Consider the following example where we compare some values (a person's age) with a constant (18):As you can see, the database can/will not decide if
NULL
is greater than/equal to 18.(B) The database will only return rows where the
WHERE
clause evaluates to True. Inverting the expression (e.g.WHERE age >= 18
changed toWHERE age < 18
) does not affect Unknown results.You can use the
IS [NOT] NULL
to matchNULL
values. The following query will select the rows where the column does not match the pattern OR the column is NULL:Functions such as
ISNULL
andCOALESCE
can be used to transformNULL
into some value.I had the same problem with the
IN
operator on simple int column with nulls. I found that these where not each others inverse as I thought. (I could tell by the row count)To get each others invert I had too rewrite them as such:
You need to check for NULL values as well:
This should take care of null values as well , which is probably why you didn't get all the rows in the output .
Does this return the correct result ?
I believe
NULL
values are the issue here, if the column contains them, thenNULL NOT LIKE '%TAX%'
will returnUNKNOWN/NULL
and therefore won't be selected.I advise you to read about handling with
NULL
values , or here.As @ughai suggested, if performance is an issue you can also use:
It happen to me once too! after breaking my head around it I found out it was because of null values, so you can use this query to avoid it: