MySQL: Filtering with Regular Expressions

Published:

Today I wanted to list all all users in a database who had been too lazy to uppercase the first letter in their name. But how can you do that in MySQL? With regular expressions such a check would be easy to write, but this was in MySQL, not in for example PHP... but wait a minute... MySQL actually supports Regular Expressions? Yes, it does! I honestly had no clue.

With my newfound knowledge about the REGEXP keyword I could write my query as simple as anything:

SELECT
  user_id,
  first_name,
  last_name
FROM
  user_details

WHERE first_name REGEXP BINARY "^[[:lower:]]"
OR last_name REGEXP BINARY "^[[:lower:]]"

ORDER BY user_id

And presto! Found them all. Always nice when you find a new handy tool to put in your belt. 👍