Match symbol '%' when searching MySQL database

I would like to match this 'wildcard %' in MySQL.
I tried using escape \% and it does not work.

+6
mysql wildcard sql-like
source share
5 answers

The default equivalent character is \ . So just the % s \ prefix like: \% :

the manual clearly says:

To check literary instances the nature of the wild card, the preceding escape character. If you do not specify the ESCAPE character, "\" is assumed.

Find % in Stack%Overflow :

 mysql> select 'Stack%Overflow' like '%\%%'; +------------------------------+ | 'Stack%Overflow' like '%\%%' | +------------------------------+ | 1 | <----- Found +------------------------------+ 1 row in set (0.00 sec) 

Find % in StackOverflow :

 mysql> select 'StackOverflow' like '%\%%'; +-----------------------------+ | 'StackOverflow' like '%\%%' | +-----------------------------+ | 0 | <----- Not Found +-----------------------------+ 1 row in set (0.00 sec) 

EDIT:

If you call this request with PHP, you will need to use \\ . This is because even PHP uses \ as an escape character. Therefore, for MySQL to get \ , you need to have \\ in PHP.

+5
source share

Here is an example:

 $sql = 'SELECT * FROM tableName WHERE fieldName LIKE "wildcard\%"'; 
0
source share

ok I need to use doble (\\) to match% in the database

0
source share

You also need to avoid the \ in PHP line, otherwise PHP will think that you are actually avoiding%, thus sending the% literal to the sql query, so I think this should work:

 mysql_query("select * from bla where bli like '\\%somewords\\%'"); 
0
source share

In the latest version you can also try

 select * from tbl1 where TxtExpr REGEXP '^%'; 

considers

0
source share

All Articles