Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NOT LIKE and LIKE not returning opposite result

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.

like image 424
Shanka Avatar asked Nov 02 '16 09:11

Shanka


People also ask

What do the like and not like operators do?

The SQL LIKE and NOT LIKE operators are used to find matches between a string and a given pattern. They are part of standard SQL and work across all database types, making it essential knowledge for all SQL users.

How do you use not like?

The NOT LIKE operator in SQL is used on a column which is of type varchar . Usually, it is used with % which is used to represent any string value, including the null character \0 . The string we pass on to this operator is not case-sensitive.

How do you use not like in query?

SQL not like statement syntax will be like below. SELECT column FROM table_name WHERE column NOT LIKE pattern; UPDATE table_name SET column=value WHERE column NOT LIKE pattern; DELETE FROM table_name WHERE column NOT LIKE pattern; As an example, let's say we want the list of customer names that don't start with 'A'.

How use NOT LIKE operator in SQL for multiple values?

So, here is the easiest solution. select * from table1 where column1 not like '%value1%' and column1 not like '%value2%' and column1 not like'%value3%'; If you want to play around with the Boolean logic, you rearrange the query like this.


1 Answers

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 
like image 77
sagi Avatar answered Sep 19 '22 12:09

sagi