6

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

Aldwoni
  • 1,168
  • 10
  • 24
RicardO
  • 1,219
  • 1
  • 14
  • 24

5 Answers5

5

The default escape character is \. So just prefix % with a \ as: \%:

The manual clearly says:

To test for literal instances of a wild-card character, precede it by the escape character. If you do not specify the ESCAPE character, “\” is assumed.

Search for % in Stack%Overflow:

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

Search for % in StackOverflow:

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

EDIT:

If you are calling this query from PHP, you'll have to use \\. This is because even PHP uses \ as the escape character. So make MySQL get a \ you need to have \\ in PHP.

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

Here is an example:

$sql = 'SELECT * FROM tableName WHERE fieldName LIKE "wildcard\%"';
Naveed
  • 41,517
  • 32
  • 98
  • 131
0

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

RicardO
  • 1,219
  • 1
  • 14
  • 24
0

You need to escape the \ in PHP string as well, otherwise PHP would think that you are actually escaping the %, thus sending literal % to the sql query, so I think this should work:

mysql_query("select * from bla where bli like '\\%somewords\\%'");
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
  • You'd only have to double escape if you were using double-quoted (`"`) strings. As is, your version will search for literal backslashes with wildcards. – Marc B Dec 04 '10 at 06:39
0

In latest version you can also try

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

regards

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118