VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
LIKE describes a shape with 2 characters. REGEXP describes one with a whole
pattern language, so it can ask for things LIKE cannot express: a choice
between alternatives, a repeated group, a character range.
Open the client with mysql -u root -p sakila before you start.
How REGEXP works
PATTERN_TEXT with the regular expression to look for.
The condition is true when the pattern matches anywhere inside the value. That
is the first difference from LIKE, which has to describe the whole value.
The pieces used below:
Examples
1) Starts with
^ the pattern would match ACA anywhere in the title.
2) Ends with
3) Either of 2 beginnings
ALBERT appears twice because 2 actors share the name. SELECT reports rows,
not distinct values.
4) A shape LIKE cannot describe
This asks for titles that begin withA or B and end with S.
5) Everything that does not match
NOT REGEXP reverses the test, the same way NOT LIKE does.
REGEXP nor NOT REGEXP, because both return
NULL for it. IS NULL covers that.
RLIKE is the same operator
RLIKE and REGEXP are 2 spellings of one operator. Pick one and keep to it.
Case, and how to insist on it
A pattern follows the collation of what it is matching, the same asLIKE. So
a lower case pattern matches upper case text by default. REGEXP_LIKE() is the
function form of the operator, and its third argument overrides that: 'c'
means case-sensitive.
Prefer LIKE when LIKE can say it
No index can narrow aREGEXP search, because a match may start anywhere, so
the server tests every value. LIKE with a pattern that starts with fixed text
can jump straight to the matching part of an index. When both can express the
filter, LIKE is the cheaper of the 2. The LIKE lesson
explains which patterns can use an index and which cannot.
Summary
- Use
REGEXPto match a pattern anywhere in a value. - Anchor with
^and$when the match has to be at the start or the end. - Read
RLIKEas another name forREGEXP. - Use
REGEXP_LIKE(value, pattern, 'c')to force a case-sensitive match. - Reach for
LIKEfirst, because no index can narrow aREGEXPsearch.
See also
- LIKE — the simpler pattern operator
- Case sensitivity — what decides the default
- WHERE — the clause the pattern goes in
- Full-text search in MySQL — searching words in text at scale
- Fuzzy string matching in MySQL — matching text that is close but not equal

