NOT LIKE and LIKE not returning opposite result
Does this return the correct result ?
Select * from tbl1 WHERE COALESCE([TextCol],'-1') NOT LIKE '%TAX%'
I believe NULL
values are the issue here, if the column contains them, then NULL NOT LIKE '%TAX%'
will return UNKNOWN/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:
Select * from tbl1
WHERE [TextCol] NOT LIKE '%TAX%'
OR [TextCol] IS NULL
(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):
21 >= 18 -- True
15 >= 18 -- False
NULL >= 18 -- Unknown
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 to WHERE age < 18
) does not affect Unknown results.
You can use the IS [NOT] NULL
to match NULL
values. The following query will select the rows where the column does not match the pattern OR the column is NULL:
WHERE [TextCol] NOT LIKE '%TAX%' OR [TextCol] IS NULL
Functions such as ISNULL
and COALESCE
can be used to transform NULL
into some value.