Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match '%' sign when searching in MySQL database

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

like image 534
RicardO Avatar asked Dec 04 '10 06:12

RicardO


People also ask

What does this symbol mean in MySQL?

MySQLi MySQLDatabase. The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0.

What means '%' in SQL?

The SQL LIKE Operator 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.

How do I find matching records in MySQL?

MySQL LIKE with Percentage % Wildcard: >> SELECT TeachName, subject FROM data. teacher WHERE subject LIKE 'C%'; Use of the percentage sign before the pattern means that the pattern will match the last location of a value.

How do I match a pattern in MySQL?

Use the LIKE or NOT LIKE comparison operators instead. The other type of pattern matching provided by MySQL uses extended regular expressions. When you test for a match for this type of pattern, use the REGEXP_LIKE() function (or the REGEXP or RLIKE operators, which are synonyms for REGEXP_LIKE() ).


1 Answers

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.

like image 54
codaddict Avatar answered Oct 21 '22 00:10

codaddict