Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "_" (underscore) match "-" (hyphen)?

Tags:

mysql

wildcard

I have to look for a PDF manual using this query:

root@localhost:test> select * from a where name like '%taz_manual%.pdf%'; +--------------------+------------------+-------------+ | name               | description      |        size |  +--------------------+------------------+-------------+ | taz-manual-1.1.pdf | Manual v1.0 TA-Z |    31351902 | | taz-manual-0.2.pdf | Manual v1.0 T1-A |     3578278 | | taz_manual-2.0.pdf | Manual v2.0 GA-X |   542578278 | etc........ +--------------------+------------------+-------------+ 132 row in set (0.00 sec) 

Why am I seeing the the one with dashes when I specify the name to be taz_manual%.pdf?

like image 275
E.G. Avatar asked Nov 23 '11 03:11

E.G.


People also ask

What is the meaning of underscore _ in the like statement?

The SQL LIKE Operator The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. 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.

Is underscore a special character in mysql?

An underscore, _ , in a LIKE expression is a wildcard as deceze mentioned in the comments. It means any single character. A backslash, \ , in a LIKE expression is an escape character. If you need to match an underscore specifically use \_ and if you need to match a backslash use \\\\ .


1 Answers

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%'; 
like image 72
Book Of Zeus Avatar answered Oct 01 '22 16:10

Book Of Zeus