Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match Underscore in String - MYSQL [duplicate]

Tags:

mysql

if column value is 2_apples or final_chapter how do i match a value that contains an underscore "_" ?

I've tried with:

SELECT DISTINCT brand FROM `items` WHERE brand like '%\\_'
SELECT DISTINCT brand FROM `items` WHERE brand like '_'
SELECT DISTINCT brand FROM `items` WHERE brand like '%_%'
SELECT DISTINCT brand FROM `items` WHERE brand like LIKE '\_' 

It either shows all results or none. Any suggestions?

like image 860
RanaHaroon Avatar asked Jul 07 '17 13:07

RanaHaroon


People also ask

How do I match an underscore in SQL?

If you are searching for an underscore then escape it with a '\' so you would search for' \_'. When matching SQL patterns, you can use these symbols as placeholders: % (percent) to substitute for zero or more characters, or _ (underscore) to substitute for one single character.

How do I match a string in MySQL?

STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.

What is the use of underscore in MySQL?

MySQL provides two wildcard characters for constructing patterns: percentage % and underscore _ . The percentage ( % ) wildcard matches any string of zero or more characters. The underscore ( _ ) wildcard matches any single character.


1 Answers

Try

WHERE brand LIKE '%\_%'

The underscore is a wildcard for a single character whereas the % is a wildcard for multiple (or none) characters. Put a backslash in front to escape them.

If you don't like escaping things, because it's ugly or scary, then an alternative would be to use the REGEXP operator with underscore directly:

WHERE brand REGEXP '_'
like image 155
fancyPants Avatar answered Sep 29 '22 23:09

fancyPants