Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wildcard for single digit mysql

Tags:

sql

mysql

I want to use the LIKE operator to match possible values in a column.

If the value begins with "CU" followed by a digit (e.g. "3") followed by anything else, I would like to return it. There only seems to be a wildcard for any single character using underscore, however I need to make sure it is a digit and not a-z. I have tried these to no avail:

select name from table1 where name like 'CU[0-9]%'
select name from table1 where name like 'CU#%'

Preferably this could be case sensitive i.e. if cu or Cu or cU then this would not be a match.

like image 302
pedromillers Avatar asked Jun 04 '13 20:06

pedromillers


People also ask

Can we use wildcard in MySQL?

MySQL WildcardsA wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

Is * a wildcard in SQL?

To broaden the selections of a structured query language (SQL-SELECT) statement, two wildcard characters, the percent sign (%) and the underscore (_), can be used. The percent sign is analogous to the asterisk (*) wildcard character used with MS-DOS.

What are the two wildcard characters used in MySQL?

The percentage wildcard is used to match any number of characters starting from zero (0) and more. The underscore wildcard is used to match exactly one character.


2 Answers

You need to use regexp:

select name
from table1
where name regexp binary '^CU[0-9]'

The documentation for regexp is here.

EDIT: binary is required to ensure case-sensitive matching

like image 121
Gordon Linoff Avatar answered Sep 28 '22 18:09

Gordon Linoff


The like operator only have the % and _ wildcards in MySQL, but you can use a regular expression with the rlike operator:

select name from table1 where name rlike '^CU[0-9]'
like image 27
Guffa Avatar answered Sep 28 '22 19:09

Guffa