I want to return rows where certain fields follow a particular pattern such as whether a particular character in a string is a letter or number. To test it out, I want to return fields where the first letter is any letter. I used this code.
SELECT * FROM sales WHERE `customerfirstname` like '[a-z]%';
It returns nothing. So I would think that the criteria is the first character is a letter and then any following characters do not matter.
The following code works, but limits rows where the first character is an a.
SELECT * FROM sales WHERE `customerfirstname` like 'a%';
Am I not understanding pattern matching? Isn’t it [a-z] or [A-Z] or [0-9] for any letter or number?
Also if I wanted to run this test on the second character in a string, wouldn’t I use
SELECT * FROM `sales` WHERE `customerfirstname` like '_[a-z]%'
This is for SQL and MySQL. I am doing this in phpmyadmin.
2
Answers
You want to use regular expressions:
This can be achieved with a regular expression.
^
denotes the start of the string, while the[:alpha]
character class matches any alphabetic character.Just in case, here are a few others character classes that you may find useful :
alnum
: dlphanumeric charactersdigit
: digit characterslower
: lowercase alphabetic charactersupper
: uppercase alphabetic charactersSee the mysql regexp docs for many more…