Home >Database >Mysql Tutorial >How to Escape the Underscore Character in a MySQL LIKE Query?
MySQL LIKE Query with Special Character _
Consider the following 'images' table:
id | img_path |
---|---|
1 | abc_1.jpg |
2 | abc_2.jpg |
3 | abcde_1.jpg |
4 | abcde_2.jpg |
5 | abcdef_1.jpg |
Problem:
You wish to retrieve entries where 'img_path' begins with 'abc_'. Using the query:
SELECT id FROM images WHERE img_path LIKE 'abc_%'
returns all five rows, not just rows with 'id' 1 and 2.
Solution:
The underscore '_' is a special character in MySQL and must be escaped using backslashes. The correct query is:
SELECT id FROM images WHERE img_path LIKE 'abc\_%'
This query accurately returns only id 1 and 2, as expected.
The above is the detailed content of How to Escape the Underscore Character in a MySQL LIKE Query?. For more information, please follow other related articles on the PHP Chinese website!