MySQL Tutorial
MySQL Installation and Configuration
MySQL Database Operations
Database Design
MySQL Data Types
MySQL Storage Engines
MySQL Basic Operations of Tables
MySQL Constraints
MySQL Operators
MySQL Function
MySQL Manipulate Table Data
MySQL View
MySQL Indexes
MySQL Stored Procedure
MySQL Trigger
MySQL Transactions
MySQL Character Set
MySQL User Management
MySQL Database Backup and Recovery
MySQL Log
MySQL Performance Optimization
REGEXP
is a powerful feature in MySQL that allows for complex pattern matching using regular expressions.
Consider the following employees
table:
id | name |
---|---|
1 | John |
2 | Jane |
3 | Alice |
4 | Bob |
5 | Charlie |
6 | David |
Here are some examples of how you can use REGEXP
:
Basic Usage
If you want to find all names that start with 'J', you can use REGEXP
like this:
SELECT * FROM employees WHERE name REGEXP '^J';
This will return:
id | name |
---|---|
1 | John |
2 | Jane |
Using a Character Set
You can also use a character set to match any single character within the set. For example, to find names that start with either 'A', 'B', or 'C', you can do:
SELECT * FROM employees WHERE name REGEXP '^[ABC]';
This will return:
id | name |
---|---|
3 | Alice |
4 | Bob |
5 | Charlie |
Using a Dot
The dot .
is a special character that matches any single character. For instance, to find names that have any character followed by 'o', you can do:
SELECT * FROM employees WHERE name REGEXP '.o';
This will return:
id | name |
---|---|
1 | John |
5 | Charlie |
Negation
You can also use NOT REGEXP
to find rows that do not match the pattern. For example, to find names that do not start with 'J', you can do:
SELECT * FROM employees WHERE name NOT REGEXP '^J';
This will return:
id | name |
---|---|
3 | Alice |
4 | Bob |
5 | Charlie |
6 | David |
Remember, regular expressions can be complex, but they're also very powerful. They're a great tool to have in your toolbox for situations where standard SQL LIKE
operator is not enough.
MySQL REGEXP Operator Example:
SELECT * FROM table_name WHERE column_name REGEXP 'pattern';
How to Use REGEXP in MySQL:
SELECT * FROM emails WHERE email_address REGEXP '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$';
Regular Expression Matching in MySQL:
SELECT * FROM sentences WHERE sentence_text REGEXP '\\bword\\b';
Case-sensitive vs Case-insensitive REGEXP in MySQL:
BINARY
keyword for case-sensitive matching.SELECT * FROM names WHERE last_name REGEXP BINARY 'Smith';
Negating Regular Expressions with NOT REGEXP in MySQL:
NOT REGEXP
to filter out rows that match the specified regular expression.SELECT * FROM products WHERE product_name NOT REGEXP 'special_offer';
Using Character Classes in MySQL REGEXP:
SELECT * FROM words WHERE word REGEXP '[aeiou]';
Optimizing Regular Expression Queries in MySQL:
CREATE INDEX idx_pattern_optimize ON table_name (column_name);
Examples of Using REGEXP in MySQL Queries:
SELECT * FROM phone_numbers WHERE phone_number REGEXP '^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$';