MySQL | Regular Expressions (Regexp)
Last Updated :
12 Apr, 2025
In MySQL, regular expressions (REGEX) offer powerful functionality for flexible pattern matching within string data. By using the REGEXP and RLIKE operators, developers can efficiently search, validate, and manipulate string data in more dynamic ways than simple LIKE
queries.
In this article, we will explain how to use SQL regular expressions, cover metacharacters, provide real-world examples, and discuss the use cases of REGEX in SQL for better query optimization and performance.
What is SQL REGEX in MySQL?
SQL REGEX refers to a powerful string-matching mechanism supported by MySQL for complex search operations. It allows developers to define custom search patterns to match strings, making it an essential tool for querying large datasets, filtering information, or validating data in database columns.
In MySQL, REGEXP
and RLIKE
are synonymous operators used for performing regular expression matching. The primary difference between REGEXP and RLIKE is that REGEXP is the standard operator, while RLIKE is just an alias for it.
How SQL REGEX Works in MySQL
The REGEXP
operator allows advanced pattern matching capabilities, which are especially useful for performing complex searches or validations. It differs from the LIKE
operator because it supports a wider variety of matching patterns and metacharacters.
Key Features:
- Advanced Pattern Matching:
REGEXP
enables more complex searches, such as matching specific character classes, ranges, and repetitions.
- Escape Sequences: The backslash (
\
) is used as an escape character in regular expressions. To use a literal backslash, you must escape it with another backslash (i.e., \\
).
- Case Insensitivity: By default, MySQL regular expressions are case-insensitive. To make them case-sensitive, you can use the
BINARY
keyword.
Commonly Used Metacharacters in SQL REGEX
MySQL’s regular expressions support a variety of metacharacters that allow complex pattern creation. Below is a list of commonly used metacharacters in regex in SQL and their functions:
Pattern |
What the Pattern matches |
* |
Zero or more instances of string preceding it |
+ |
One or more instances of strings preceding it |
. |
Any single character |
? |
Match zero or one instances of the strings preceding it. |
^ |
caret(^) matches Beginning of string |
$ |
End of string |
[abc] |
Any character listed between the square brackets |
[^abc] |
Any character not listed between the square brackets |
[A-Z] |
match any upper case letter. |
[a-z] |
match any lower case letter |
[0-9] |
match any digit from 0 through to 9. |
[[:<:]] |
matches the beginning of words. |
[[:>:]] |
matches the end of words. |
[:class:] |
matches a character class i.e. [:alpha:] to match letters, [:space:] to match white space, [:punct:] is match punctuations and [:upper:] for upper class letters. |
p1|p2|p3 |
Alternation; matches any of the patterns p1, p2, or p3 |
{n} |
Exactly n instances of preceding element |
{m,n} |
between m and n instances of preceding element |
Examples of SQL REGEX in MySQL
Here are several practical examples demonstrating how to use SQL regular expressions in MySQL queries to achieve dynamic pattern matching:
1. Match beginning of string(^)
To match all names starting with “sa“, we use the caret (^) symbol to specify the beginning of the string.
Example:
SELECT name FROM student_tbl WHERE name REGEXP '^sa';
This will match names like sam
and samarth
.
2. Match the end of a string($)
To match all names ending with “on”, we use the dollar sign ($) to signify the end of the string.
Example:
SELECT name FROM student_tbl WHERE name REGEXP 'on$';
This will match names like norton
and merton
.
3. Match zero or one instance of the strings preceding it(?)
To find all movie titles containing “com” with optional spaces following it (e.g., “com” or “com “), you can use the question mark (?
)
Example:
SELECT title FROM movies_tbl WHERE title REGEXP 'com ?';
This will match titles like comedy
and romantic comedy
4. Matches any of the patterns p1, p2, or p3(p1|p2|p3)
The pipe ( |
) operator allows you to match any of the specified patterns. In this case, it matches names that contain either “be” or “ae”.
Example:
SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ;
This will match names like Abel
and Baer
.
5. Matches any character listed between the square brackets([abc])
The square brackets []
in SQL regular expressions allow us to match any single character listed inside them. Gives all the names containing ‘j’ or ‘z’ anywhere in the string.
Example:
SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ;
This will match names like Lorentz
and Rajs
6. Matches any lower case letter between ‘a’ to ‘z’- ([a-z]) ([a-z] and (.))
The pattern ([a-z] and .)
in SQL regex is used to match a lowercase letter within a specified range, followed by any single character, and then another specified character. This query will retrieve names containing a letter between ‘b’ and ‘g’, followed by any character, and ending with the letter ‘a’.
Example:
SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ;
This will match names like Tobias
and sewall
7. Matches any character not listed between the square brackets.([^abc])
The pattern [^abc]
in SQL regex is used to match any character that is not listed between the square brackets. This query retrieves all names that do not contain the characters ‘j’ or ‘z’.
Example:
SELECT name FROM student_tbl WHERE name REGEXP '^[^jz]*$';
This will exclude names containing ‘j’ or ‘z’, such as nerton
and sewall
8. Matches the end of words[[:>:]]
The pattern [[:>:]]
in SQL regex is a word boundary metacharacter that matches the end of a word. This query retrieves all titles where a word ends with “ack”.
Example:
SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]';
This will match titles like Black
.
9. Matches the beginning of words[[:<:]]
The pattern [[:<:]]
in SQL regex is a word boundary metacharacter that matches the beginning of a word. Gives all the titles starting with character “for“.
Example:
SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for';
This will match titles like Forgetting Sarah Marshall
10. Matches a character class[:class:]
The [:class:]
pattern in SQL regular expressions matches a specific character class, providing flexibility in filtering data based on character types. Gives all the titles containing alphabetic character only.
Example:
SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ;
This will match titles like Stranger Things
and Avengers
11. Matches the beginning of all words by any character listed between the square brackets.(^[abc])
The pattern ^[abc]
matches strings where the first character of the word belongs to the specified set of characters (in this case, a, b, or c). Gives all the names starting with ‘n‘ or ‘s‘.
Example:
SELECT name FROM student_tbl WHERE name REGEXP '^[ns]' ;
This will match names like nerton
and sewall
Conclusion
SQL REGEX in MySQL offers advanced pattern matching capabilities that allow us to perform complex queries and improve data manipulation in our databases. By using REGEXP and RLIKE operators, we can create dynamic search conditions that are highly useful for validating, filtering, and retrieving data. Understanding regular expressions will greatly enhance our SQL querying skills and improve database performance, especially for complex datasets.
Similar Reads
Python MySQL
Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library. This Python MySQL tutorial will
9 min read
How to install MySQL Connector Package in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. A connector is employed when we have to use MySQL with other pro
2 min read
Connect MySQL database using MySQL-Connector Python
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with
3 min read
How to Install MySQLdb module for Python in Linux?
In this article, we are discussing how to connect to the MySQL database module for python in Linux. MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0 and is built on top of the MySQL C API. Installing MySQLdb module for Python o
2 min read
MySQL Queries
Python MySQL - Select Query
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mySQL, PostgreSQL, Microsoft SQL Server 2000
2 min read
CRUD Operation in Python using MySQL
In this article, we will be seeing how to perform CRUD (CREATE, READ, UPDATE and DELETE) operations in Python using MySQL. For this, we will be using the Python MySQL connector. For MySQL, we have used Visual Studio Code for python. Before beginning we need to install the MySQL connector with the co
6 min read
Python MySQL - Create Database
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000,
2 min read
Python MySQL - Update Query
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Update Clause The update is used to ch
2 min read
Python MySQL - Insert into Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify
3 min read
Python MySQL - Insert record if not exists in table
In this article, we will try to insert records and check if they EXISTS or not. The EXISTS condition in SQL is used to check if the result of a correlated nested query is empty (contains no tuples) or not. It can be used to INSERT, SELECT, UPDATE, or DELETE statements. Pre-requisite Connect MySQL Da
4 min read
Python MySQL - Delete Query
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Databases such as MySQL, GadFly, PostgreSQL, Microsoft SQL Server 2000, Info
3 min read
MySQL Working with Data
MySQL | Regular Expressions (Regexp)
In MySQL, regular expressions (REGEX) offer powerful functionality for flexible pattern matching within string data. By using the REGEXP and RLIKE operators, developers can efficiently search, validate, and manipulate string data in more dynamic ways than simple LIKE queries. In this article, we wil
7 min read
SQL Query to Match Any Part of String
It is used for searching a string or a sub-string to find a certain character or group of characters from a string. We can use the LIKE Operator of SQL to search sub-strings. The LIKE operator is used with the WHERE Clause to search a pattern in a string of columns. The LIKE operator is used in conj
3 min read
SQL Auto Increment
In SQL databases, a primary key is important for uniquely identifying records in a table. However, sometimes it is not practical to manually assign unique values for each record, especially when handling large datasets. To simplify this process, SQL databases offer an Auto Increment feature that aut
6 min read
SQL Query to Delete Duplicate Rows
Duplicate rows in a database can cause inaccurate results, waste storage space, and slow down queries. Cleaning duplicate records from our database is an essential maintenance task for ensuring data accuracy and performance. Duplicate rows in a SQL table can lead to data inconsistencies and performa
6 min read
SQL Query to Convert an Integer to Year Month and Days
With this article, we will be knowing how to convert an integer to Year, Month, Days from an integer value. The prerequisites of this article are you should be having a MSSQL server on your computer. What is a query? A query is a statement or a group of statements written to perform a specific task,
2 min read
Calculate the Number of Months between two specific dates in SQL
In this article, we will discuss the overview of SQL Query to Calculate the Number of Months between two specific dates and will implement with the help of an example for better understanding. Let's discuss it step by step. Overview :Here we will see, how to calculate the number of months between th
3 min read
How to Compare Two Queries in SQL
Queries in SQL :A query will either be an invitation for data results from your info or for action on the info, or each. a question will provide you with a solution to a straightforward question, perform calculations, mix data from totally different tables, add, change, or delete data from info. Cre
2 min read
Joining 4 Tables in SQL
The purpose of this article is to make a simple program to Join two tables using Join and Where clause in SQL. Below is the implementation for the same using MySQL. The prerequisites of this topic are MySQL and the installment of Apache Server on your computer. Introduction :In SQL, a query is a req
3 min read
MySQL Working with Images
Working with MySQL BLOB in Python
In Python Programming, We can connect with several databases like MySQL, Oracle, SQLite, etc., using inbuilt support. We have separate modules for each database. We can use SQL Language as a mediator between the python program and database. We will write all queries in our python program and send th
4 min read
Retrieve Image and File stored as a BLOB from MySQL Table using Python
Prerequisites: MySQL server should be installed In this post, we will be talking about how we can store files like images, text files, and other file formats into a MySQL table from a python script. Sometimes, just like other information, we need to store images and files into our database and provi
3 min read
How to read image from SQL using Python?
In this article, we are going to discuss how to read an image or file from SQL using python. For doing the practical implementation, We will use MySQL database. First, We need to connect our Python Program with MySQL database. For doing this task, we need to follow these below steps: Steps to Connec
3 min read
Boutique Management System using Python-MySQL Connectivity
In this article, we are going to make a simple project on a boutique management system using Python MySql connectivity. Introduction This is a boutique management system made using MySQL connectivity with Python. It uses a MySQL database to store data in the form of tables and to maintain a proper r
15+ min read