Regular Expressions in SQL
Pattern matching beyond LIKE: regular expression syntax, matching with ~ and REGEXP_LIKE, extracting matches and capture groups, replacing with back-references, validating values with CHECK constraints, greedy and lazy quantifiers, splitting on patterns, and the differences between databases.
kvi5hnuCode Sprout team member10 min readOn this page
LIKE (article 7) knows two wildcards: % for any text and _ for one character. That's enough for "starts with Ridge" but not for "contains an order number", "looks like a phone number" or "is a valid product code". Regular expressions describe the structure of text: which kinds of characters, how many, in what order. Every major database supports them, with different function names and a few traps.
This article covers the pattern syntax, then matching, extracting, replacing, validating and splitting. The examples use a table of customer messages:
CREATE TABLE messages (msg_id INTEGER PRIMARY KEY, body TEXT NOT NULL);
-- 1 'Order #104 arrived damaged, call me on 020 7946 0018'
-- 2 'Please change order #102 to the Ridge 2 tent'
-- 3 'Email ASHA.RAO@example.com about orders #101 and #103'
-- 4 'Is the Summit 4 tent waterproof?'
-- 5 'refund for order #105 please'
Pattern syntax
A regular expression is made of a few kinds of pieces:
| Piece | Meaning | Example |
|---|---|---|
| ordinary characters | themselves | tent matches "tent" |
. | any one character | t.nt matches "tent", "tint" |
[abc], [a-z], [^0-9] | one character from a set, a range, or not in a set | [A-Z] is one capital letter |
\d, \s, \w | a digit, a whitespace character, a word character | \d\d is two digits |
[[:digit:]], [[:alpha:]], [[:alnum:]], [[:space:]] | POSIX classes, supported everywhere | [[:digit:]] = [0-9] |
*, +, ? | repeat the previous piece 0 or more, 1 or more, 0 or 1 times | \d+ is one or more digits |
{n}, {n,}, {n,m} | exactly n, at least n, between n and m times | \d{4} is four digits |
^, $ | the start and end of the text | ^Ridge must start with "Ridge" |
a|b | either alternative | tent|tarp |
( ) | group, and capture what matched | #(\d+) captures the number |
\., \?, \( | a special character taken literally | \?$ ends with a question mark |
![The pattern ^[A-Z]{3}-[0-9]{4}$ broken into its parts: start anchor, one capital letter repeated exactly three times, a literal hyphen, one digit repeated exactly four times, end anchor; TEN-0001 matches, while ten-0001, XTEN-00012 and TEN-01 don't](https://code-sprout-content.laxmi.solutions/asset/2026/11/sql-regex-anatomy-c7ls62qqxy4fc2qv.png)
Unlike LIKE, a regular expression matches if it's found anywhere in the text. To match the whole value, anchor it with ^ and $.
Matching: does the text fit the pattern?
-- Messy text to search and clean
CREATE TABLE messages (
msg_id INTEGER PRIMARY KEY,
body TEXT NOT NULL
);
INSERT INTO messages VALUES
(1, 'Order #104 arrived damaged, call me on 020 7946 0018'),
(2, 'Please change order #102 to the Ridge 2 tent'),
(3, 'Email ASHA.RAO@example.com about orders #101 and #103'),
(4, 'Is the Summit 4 tent waterproof?'),
(5, 'refund for order #105 please');
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- ~ matches a regular expression (case-sensitive); ~* ignores case; !~ negates
SELECT msg_id,
body ~ 'order #[0-9]+' AS has_order_ref,
body ~* 'ORDER #[0-9]+' AS has_order_ref_any_case,
body ~ '\d{3} \d{4} \d{4}' AS has_phone,
body ~ '\?$' AS ends_with_question
FROM messages
ORDER BY msg_id;
-- LIKE can only match fixed text and wildcards; regex can describe structure
SELECT name
FROM products
WHERE name ~ '^[A-Z][a-z]+ [0-9]+ ' -- a capitalised word, a space, a number, a space
ORDER BY name;
msg_id | has_order_ref | has_order_ref_any_case | has_phone | ends_with_question
--------+---------------+------------------------+-----------+--------------------
1 | f | t | t | f
2 | t | t | f | f
3 | f | f | f | f
4 | f | f | f | t
5 | t | t | f | f
(5 rows)
name
-------------------
Day 18 backpack
Ridge 2 tent
Summit 4 tent
Trail 30 backpack
(4 rows)
PostgreSQL's matching operators are ~ (matches, case-sensitive), ~* (matches, ignoring case), and !~ and !~* for "doesn't match". regexp_like(text, pattern, flags) (PostgreSQL 15+) does the same as a function.
The results are worth reading closely:
- Message 1 starts with "Order", with a capital O, so the case-sensitive
order #[0-9]+doesn't match it, while~*does. - Message 3 mentions "orders #101": the pattern requires
orderfollowed directly by a space and#, so the "s" stops it. Regular expressions are exact about every character. \d{3} \d{4} \d{4}finds the London phone number in message 1, and\?$finds the message ending with a question mark.- The product query finds names shaped like "capitalised word, space, number, space".
LIKEcan't express "one or more digits".
Elsewhere, MySQL has REGEXP (or RLIKE) and REGEXP_LIKE(text, pattern, flags), Oracle has REGEXP_LIKE, and SQL Server 2025 added REGEXP_LIKE and the rest of the REGEXP_ family. Earlier SQL Server versions have no regular expressions: LIKE supports [a-z] sets, but no repetition. SQLite has a REGEXP operator, but it only works if a regular expression function has been loaded. The sqlite3 command-line shell includes one, but many applications don't.
Case sensitivity differs: in MySQL, matching follows the column's collation, which is usually case-insensitive, so 'Order #104' REGEXP 'order #[0-9]+' is true. Add the 'c' flag to REGEXP_LIKE for a case-sensitive match. In PostgreSQL and Oracle, matching is case-sensitive unless you ask otherwise (~* or the 'i' flag).
Extracting what matched
-- Messy text to search and clean
CREATE TABLE messages (
msg_id INTEGER PRIMARY KEY,
body TEXT NOT NULL
);
INSERT INTO messages VALUES
(1, 'Order #104 arrived damaged, call me on 020 7946 0018'),
(2, 'Please change order #102 to the Ridge 2 tent'),
(3, 'Email ASHA.RAO@example.com about orders #101 and #103'),
(4, 'Is the Summit 4 tent waterproof?'),
(5, 'refund for order #105 please');
\pset null '(null)'
-- Extract the first match, and the text captured by a group
SELECT msg_id,
SUBSTRING(body FROM '#[0-9]+') AS first_ref,
(regexp_match(body, '#([0-9]+)'))[1] AS first_order_number,
regexp_substr(body, '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[a-z]{2,}', 1, 1, 'i') AS email
FROM messages
ORDER BY msg_id;
-- Every match, one row each: regexp_matches with the 'g' flag
SELECT msg_id, m[1] AS order_number
FROM messages,
regexp_matches(body, '#([0-9]+)', 'g') AS m
ORDER BY msg_id, order_number;
msg_id | first_ref | first_order_number | email
--------+-----------+--------------------+----------------------
1 | #104 | 104 | (null)
2 | #102 | 102 | (null)
3 | #101 | 101 | ASHA.RAO@example.com
4 | (null) | (null) | (null)
5 | #105 | 105 | (null)
(5 rows)
msg_id | order_number
--------+--------------
1 | 104
2 | 102
3 | 101
3 | 103
5 | 105
(5 rows)
SUBSTRING(text FROM pattern)returns the first match. If the pattern contains a group in parentheses, it returns what the group matched instead.regexp_match(text, pattern)returns an array of the captured groups for the first match, so[1]gives the first group: the order number without the#.regexp_substr(text, pattern, start, n, flags)(PostgreSQL 15+, also in Oracle, MySQL and SQL Server 2025) returns the nth match. Here, with the'i'flag, it extracts an email address. Matching emails reliably is notoriously hard: this pattern is fine for picking addresses out of text, but don't use a regular expression as proof that an address works.- Text without a match gives NULL, as message 4 shows.
regexp_matches(text, pattern, 'g')returns one row per match with the'g'(global) flag. Message 3 mentions two orders, so it produces two rows. Used in theFROMclause next to the table, it acts as a lateral join (article 23).
Turning every order number in free text into rows is a typical task for regular expressions: the result can now be joined to orders.
Replacing
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Messy text to search and clean
CREATE TABLE messages (
msg_id INTEGER PRIMARY KEY,
body TEXT NOT NULL
);
INSERT INTO messages VALUES
(1, 'Order #104 arrived damaged, call me on 020 7946 0018'),
(2, 'Please change order #102 to the Ridge 2 tent'),
(3, 'Email ASHA.RAO@example.com about orders #101 and #103'),
(4, 'Is the Summit 4 tent waterproof?'),
(5, 'refund for order #105 please');
-- Replace with patterns; 'g' replaces every match, not just the first
SELECT msg_id,
regexp_replace(body, '\s+', ' ', 'g') AS single_spaces,
regexp_replace(body, '\d{3} \d{4} (\d{4})', '*** **** \1') AS phone_masked
FROM messages
WHERE msg_id IN (1, 5)
ORDER BY msg_id;
-- Back-references: swap "First Last" into "Last, First"
SELECT name, regexp_replace(name, '^(\S+) (\S+)$', '\2, \1') AS last_first
FROM customers
WHERE customer_id <= 3
ORDER BY customer_id;
-- Keep only digits, and count matches (PostgreSQL 15+)
SELECT regexp_replace('+44 (0)20 7946-0018', '[^0-9]', '', 'g') AS digits_only,
regexp_count('Order #101 and #103', '#\d+') AS order_refs;
msg_id | single_spaces | phone_masked
--------+------------------------------------------------------+------------------------------------------------------
1 | Order #104 arrived damaged, call me on 020 7946 0018 | Order #104 arrived damaged, call me on *** **** 0018
5 | refund for order #105 please | refund for order #105 please
(2 rows)
name | last_first
------------+-------------
Asha Rao | Rao, Asha
Ben Okafor | Okafor, Ben
Chen Wei | Wei, Chen
(3 rows)
digits_only | order_refs
---------------+------------
4402079460018 | 2
(1 row)
regexp_replace(text, pattern, replacement, flags) replaces matches:
- Without the
'g'flag, PostgreSQL replaces only the first match.regexp_replace(body, '\s+', ' ', 'g')collapses every run of whitespace into a single space, tidying message 5. This differs between databases: MySQL, Oracle and SQL Server replace every match by default. - In the replacement,
\1,\2and so on insert what the groups captured. The masking example keeps the last group of digits of the phone number and stars out the rest. Swapping "First Last" into "Last, First" uses two groups. MySQL writes these back-references as$1,$2. [^0-9]matches anything that isn't a digit, so replacing it with nothing keeps only the digits, a common way to normalise phone numbers before comparing them.regexp_count(PostgreSQL 15+) counts the matches.
Validating values
-- Validating values with a pattern: anchors ^ and $ make the whole value match
SELECT code,
code ~ '^[A-Z]{3}-[0-9]{4}$' AS valid_sku,
code ~ '[A-Z]{3}-[0-9]{4}' AS contains_sku
FROM (VALUES ('TEN-0001'), ('ten-0001'), ('XTEN-00012'), ('TEN-01')) AS t(code);
-- A CHECK constraint keeps bad values out
CREATE TABLE skus (sku TEXT PRIMARY KEY CHECK (sku ~ '^[A-Z]{3}-[0-9]{4}$'));
INSERT INTO skus VALUES ('TEN-0001');
INSERT INTO skus VALUES ('TEN-1');
code | valid_sku | contains_sku
------------+-----------+--------------
TEN-0001 | t | t
ten-0001 | f | f
XTEN-00012 | f | t
TEN-01 | f | f
(4 rows)
psql:/workspace/solution.sql:10: ERROR: new row for relation "skus" violates check constraint "skus_sku_check"
DETAIL: Failing row contains (TEN-1).
Validation needs the anchors. [A-Z]{3}-[0-9]{4} without them finds a valid-looking code inside XTEN-00012 and accepts it. ^[A-Z]{3}-[0-9]{4}$ requires the whole value to have exactly that shape.
A CHECK constraint (article 52) with a pattern keeps malformed values out of a table for good: the second INSERT fails. This is much safer than validating only in the application, which is one of several ways data can arrive.
Greedy and lazy, and splitting
-- Greedy versus lazy quantifiers
SELECT SUBSTRING('<b>bold</b> and <i>italic</i>' FROM '<.+>') AS greedy,
SUBSTRING('<b>bold</b> and <i>italic</i>' FROM '<.+?>') AS lazy;
-- Splitting on a pattern: any run of spaces, commas or semicolons
SELECT regexp_split_to_table('tents, packs;lighting ,clothing', '[\s,;]+') AS category;
greedy | lazy
-------------------------------+------
<b>bold</b> and <i>italic</i> | <b>
(1 row)
category
----------
tents
packs
lighting
clothing
(4 rows)
Quantifiers are greedy: .+ matches as much as it can, so <.+> runs from the first < to the last >. Adding ? makes a quantifier lazy, matching as little as possible: <.+?> stops at the first >. Use lazy quantifiers, or better, a negated set such as <[^>]+>, when a pattern should stop at the first closing character. (Don't use regular expressions to process real HTML: use a proper parser in the application.)
regexp_split_to_table(text, pattern) splits text wherever the pattern matches, one row per piece, and regexp_split_to_array returns an array. Splitting on [\s,;]+ handles a messy list where items are separated by commas, semicolons, spaces or any mixture of them, which string_to_table (article 37) can't.
Differences between databases
| Task | PostgreSQL | MySQL 8+ | Oracle | SQL Server 2025 |
|---|---|---|---|---|
| matches | ~, ~*, regexp_like | REGEXP, REGEXP_LIKE | REGEXP_LIKE | REGEXP_LIKE |
| extract | SUBSTRING ... FROM, regexp_substr, regexp_match | REGEXP_SUBSTR | REGEXP_SUBSTR | REGEXP_SUBSTR |
| replace | regexp_replace (first match unless 'g') | REGEXP_REPLACE (all) | REGEXP_REPLACE (all) | REGEXP_REPLACE (all) |
| count, position | regexp_count, regexp_instr | REGEXP_INSTR | REGEXP_COUNT, REGEXP_INSTR | REGEXP_COUNT, REGEXP_INSTR |
| back-reference | \1 | $1 | \1 | \1 |
Other traps:
- Backslashes in MySQL string literals. MySQL treats
\as an escape character in strings, so'\d'reaches the regex engine as justd. Write'\\d', or use[0-9]and the POSIX classes, which need no backslashes. PostgreSQL's standard strings pass\dthrough unchanged. - Syntax flavours. PostgreSQL uses its own engine (close to Perl's), MySQL uses ICU, Oracle follows POSIX with some Perl extensions, and SQL Server 2025 uses RE2. The basics in the syntax table work everywhere, but advanced features like lookahead don't.
SIMILAR TOis a standard operator that mixesLIKEwildcards with regular expression syntax. It's rarely the best choice: useLIKEor a real regular expression.
Performance
Regular expressions are slower than plain comparisons, and an ordinary B-tree index can't help with an unanchored pattern such as ~ 'tent', so the database checks every row. Some practical advice:
- Use
LIKE 'prefix%'or=when they're enough. - Filter with cheap conditions first, so the pattern runs on fewer rows.
- In PostgreSQL, a trigram index (
pg_trgmextension with a GIN index) can speed upLIKE '%text%'and many regular expression searches (article 55). - To search for words in documents, use full-text search rather than patterns.
What's current
- SQL Server 2025 (November 2025) added
REGEXP_LIKE,REGEXP_REPLACE,REGEXP_SUBSTR,REGEXP_INSTR,REGEXP_COUNT,REGEXP_MATCHESandREGEXP_SPLIT_TO_TABLE. Before it, regular expressions in SQL Server required CLR functions. - PostgreSQL 15 added
regexp_like,regexp_count,regexp_instrandregexp_substr, matching the names used by Oracle. - MySQL 8.0 switched to the ICU engine and added
REGEXP_LIKE,REGEXP_REPLACE,REGEXP_SUBSTRandREGEXP_INSTR.
Common questions
When should I use a regular expression instead of LIKE?
When you need character classes, repetition counts, alternatives, or to extract or replace parts of text. For a fixed prefix or substring, LIKE is simpler and often faster.
Why does my pattern match more than I expected?
It's probably unanchored, so it matches anywhere in the text, or it uses a greedy quantifier. Add ^ and $, or make the quantifier lazy.
Why does regexp_replace only change the first occurrence in PostgreSQL?
PostgreSQL replaces only the first match unless you pass the 'g' flag.
Why doesn't \d work in MySQL?
MySQL string literals treat the backslash as an escape, so write \\d or [0-9].
How do I get every match, not just the first?
regexp_matches(text, pattern, 'g') in PostgreSQL returns one row per match. In other databases, loop over the occurrence argument of REGEXP_SUBSTR with a series of numbers.
Can I validate emails with a regular expression? You can check that a value roughly looks like an address, which catches typos. Only sending a message proves that an address works.
Summary
- Regular expressions describe text structure with character sets, quantifiers, anchors, alternatives and groups.
- A pattern matches anywhere in the text unless anchored with
^and$. - PostgreSQL matches with
~and~*. Other databases useREGEXP_LIKEorREGEXP. Case sensitivity defaults differ. - Extract with
SUBSTRING ... FROM,regexp_matchandregexp_substr, and get every match as rows withregexp_matches(..., 'g'). regexp_replacereplaces matches, with\1back-references. PostgreSQL needs'g'to replace every match.- Validate with anchored patterns in
CHECKconstraints. - Quantifiers are greedy, and
?makes them lazy.regexp_split_to_tablesplits on a pattern. - Regular expressions can't use ordinary indexes: prefer
LIKE, trigram indexes or full-text search where they fit.
Practice questions
Which of these values does ~ '^\d{3}-\d{4}$' match: 555-0123, 555-01234, x555-0123, 5550123?
Answer
Only 555-0123. 555-01234 has five digits after the hyphen, x555-0123 has an extra character at the start, and 5550123 has no hyphen. The anchors require the whole value to match.
Write a query that returns each message's ID and the first number that appears in it, or NULL.
Answer
SELECT msg_id, SUBSTRING(body FROM '\d+') AS first_number
FROM messages
ORDER BY msg_id;
It returns 104, 102, 101, 4 (from "Summit 4") and 105.
What does regexp_replace('a-b-c', '-', '+') return in PostgreSQL, and what does REGEXP_REPLACE('a-b-c', '-', '+') return in MySQL?
Answer
a+b-c in PostgreSQL, which replaces only the first match without the 'g' flag, and a+b+c in MySQL, which replaces every match.
Write an expression that turns 2026-03-08 into 08/03/2026 using a regular expression.
Answer
regexp_replace('2026-03-08', '^(\d{4})-(\d{2})-(\d{2})$', '\3/\2/\1')
The three groups capture year, month and day, and the replacement puts them back in a different order. For real dates, TO_CHAR(date, 'DD/MM/YYYY') (article 39) is clearer.
What does SUBSTRING('"a" and "b"' FROM '"(.*)"') return, and how do you get just a?
Answer
a" and "b. The greedy .* runs to the last quote. Use the lazy "(.*?)" or the negated set "([^"]*)", which both return a.
Previous: Working With Calendars in SQL: Month Boundaries, Date Series and Missing Dates

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.