Last chance! 50% off DataCamp Premium
Sale ends in
The REGEXP keyword in MySQL is used for pattern matching using regular expressions. It allows you to search for complex patterns in strings within your database tables.
The REGEXP keyword is typically used in the WHERE clause to filter records based on whether a string matches a specified regular expression pattern. It is a powerful tool for text searching and pattern recognition. MySQL's regular expressions are based on the POSIX standard and may differ slightly from other regex implementations.
SELECT column_name
FROM table_name
WHERE column_name REGEXP 'pattern';
In this syntax, REGEXP 'pattern' checks if column_name matches the given regular expression pattern. Note that REGEXP is case-insensitive by default. To perform case-sensitive matching, use the BINARY keyword:
SELECT column_name
FROM table_name
WHERE BINARY column_name REGEXP 'pattern';
SELECT *
FROM products
WHERE product_name REGEXP '^C';
This example selects all rows from the products table where product_name starts with the letter 'C'. The '^C' pattern uses ^ to indicate the start of the string, ensuring that only names beginning with 'C' are matched.
SELECT email
FROM users
WHERE email REGEXP 'gmail|yahoo';
Here, the query retrieves emails from the users table that contain either 'gmail' or 'yahoo'.
SELECT phone_number
FROM contacts
WHERE phone_number REGEXP '^[0-9]{3}-[0-9]{3}-[0-9]{4}$';
This example selects phone numbers from contacts matching the pattern for North American phone numbers in the format XXX-XXX-XXXX.
EXPLAIN to analyze query performance when using regular expressions.^ and $ to denote the start and end of a string, respectively, for more precise pattern matching.\.:WHERE column_name REGEXP '\\.'
REGEXP, which supports complex patterns, LIKE is used for simpler pattern matching with wildcards % and _. Use LIKE for straightforward patterns and REGEXP for more complex requirements.