Skip to main content

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

Replace 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

Without ^ 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 with A or B and end with S.

5) Everything that does not match

NOT REGEXP reverses the test, the same way NOT LIKE does.
A NULL value matches neither 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 as LIKE. 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 a REGEXP 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 REGEXP to match a pattern anywhere in a value.
  • Anchor with ^ and $ when the match has to be at the start or the end.
  • Read RLIKE as another name for REGEXP.
  • Use REGEXP_LIKE(value, pattern, 'c') to force a case-sensitive match.
  • Reach for LIKE first, because no index can narrow a REGEXP search.

See also