Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL 'LIKE' query using '%' where the search criteria contains '%'

I have an SQL query as below.

Select * from table 
where name like '%' + search_criteria + '%' 

If search_criteria = 'abc', it will return data containing xxxabcxxxx which is fine.

But if my search_criteria = 'abc%', it will still return data containing xxxabcxxx, which should not be the case.

How do I handle this situation?

like image 756
pratik Avatar asked May 29 '12 16:05

pratik


People also ask

What does LIKE '%' mean in SQL?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

What is %s in SQL query?

%s is a placeholder used in functions like sprintf. Check the manual for other possible placeholders. $sql = sprintf($sql, "Test"); This would replace %s with the string "Test".

How do you do multiple like conditions in SQL?

Using the LIKE operator, you can specify single or multiple conditions. This allows you to perform an action such as select, delete, and updating any columns or records that match the specified conditions. It is mainly paired with a where clause to set the conditions.


3 Answers

If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]

... where name like '%' + replace(search_criteria, '%', '[%]') + '%' 
like image 75
Alex K. Avatar answered Sep 23 '22 21:09

Alex K.


Use an escape clause:

select *
  from (select '123abc456' AS result from dual
        union all
        select '123abc%456' AS result from dual
       )
  WHERE result LIKE '%abc\%%' escape '\'

Result

123abc%456

You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.

See List of special characters for SQL LIKE clause

like image 40
Glenn Avatar answered Sep 20 '22 21:09

Glenn


The easiest solution is to dispense with "like" altogether:

Select * 
from table
where charindex(search_criteria, name) > 0

I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.

like image 37
Gordon Linoff Avatar answered Sep 22 '22 21:09

Gordon Linoff