Why does "_" (underscore) match "-" (hyphen)?
Because the underscore _
is a wildcard like the percent %
, except that it only looks for one character.
SQL pattern matching enables you to use "_" to match any single character and "%" to match an arbitrary number of characters (including zero characters).
(From section 3.3.4.7. Pattern Matching in the MySQL documentation.)
If you want to use the underscore in like
as a literal, you have to escape it:
select * from a where name like '%taz\_manual%.pdf%';
I had a similar issue with space and hyphens while matching strings with exact match:
SELECT id FROM location WHERE name = 'IND - HQ';
The above query didn't return any records in MySQL. I had to escape the spaces and hyphens and use LIKE
instead of exact match with equals (=) as follows:
SELECT id FROM location WHERE name LIKE 'IND_\-_HQ';