Although I do not believe MySQL supports regular-expression-like character classes in []
with a regular LIKE
clause (nor can I find relevant documentation), MySQL does have a REGEXP/RLIKE
operator with which you can construct a regular expression for comparable functionality.
SELECT * FROM customers WHERE lname REGEXP '^[0-9]' ORDER BY lname ASC
SELECT * FROM customers WHERE lname REGEXP '^[a-d]' ORDER BY lname ASC
To build a regular expression similar to the wildcard patterns you used, start with ^
to left-anchor the pattern, and use the same character class [0-9], [a-f]
as you proposed. You do not need to follow it by anything, because the %
wildcard would be equivalent to a match of any zero or more characters following the initial left-anchored letter or number matched by ^[]
.
Of course, you can combine those statements with a logical OR
, or build a regular expression which matches either case.
SELECT * FROM customers WHERE lname REGEXP '^[a-d]|[0-9]' ORDER BY lname ASC
Here's a demonstration.
One thing to keep in mind however: MySQL will not be able to use any index you may have on lname
when using REGEXP
.
n.b. I believe MS SQL Server supports a syntax similar to what you proposed.