Regular Expressions in SQL (REGEXP_MATCHES, REGEXP_REPLACE, ~)
Match and rewrite text with SQL regex operators when LIKE is not enough.
In plain words
A regex is a pattern describing what text should look like, so the database can find, check or change text that fits it.
Think of it like…
A sorting machine with a detailed template instead of a simple label check: LIKE asks "does it start with 'IN'?", while a regex asks "is it exactly two letters, a dash, then six digits?".
Where you’ve seen it
Pulling order numbers out of support messages: SELECT id, (regexp_match(body, 'ORD-([0-9]{6})'))[1] AS order_no FROM tickets WHERE body ~ 'ORD-[0-9]{6}'; and keeping only valid Indian PIN codes: WHERE pincode ~ '^[1-9][0-9]{5}$'.
Words you’ll hear
- ~ / ~* / !~
- PostgreSQL: matches, matches ignoring case, doesn't match.
- Anchors ^ and $
- Start and end of the string; without them a pattern can match anywhere.
- Capture group ( )
- Part of the pattern whose matched text you can extract.
- 'g' flag
- In PostgreSQL's regexp_replace, replace every match, not just the first.
Visual diagram
Theory & example queries
Matching and validating
col ~ 'pattern' is true when the pattern matches anywhere in the string. For validation, anchor it: '^[0-9]{6}$' means exactly six digits, while '[0-9]{6}' would also accept 'abc1234567xyz'. Common building blocks: [0-9] or \d (a digit), [A-Za-z], . (any character), *, + and {m,n} for repetition, and (a|b) for alternatives.
Regex makes a good CHECK constraint for formats that must always be right, such as CHECK (pincode ~ '^[1-9][0-9]{5}$'). Avoid trying to validate everything this way: email addresses, for example, are better checked loosely in SQL and properly in the application.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
SELECT id, phoneFROM customersWHERE phone !~ '^[6-9][0-9]{9}$';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative invalid phone rows3 sample rows
| id | phone |
|---|---|
| 42 | +91 9876543210 |
| 58 | 5123456789 |
| 71 | 98765-43210 |
Note: The sample assumes the phone column is non-NULL; NULL values do not satisfy !~ and are not returned. Regex support and NULL behavior shown are PostgreSQL-specific.
lists Indian mobile numbers that aren't exactly 10 digits starting with 6–9.
Key takeaway: Anchor patterns used for validation.
Extracting, replacing and performance
regexp_match(text, pattern) returns an array of capture groups from the first match; regexp_matches(…, 'g') returns every match as rows; substring(text from pattern) returns the first capture group as text. regexp_replace(text, pattern, replacement, 'g') rewrites matches, and the 'g' flag matters: without it PostgreSQL replaces only the first match. PostgreSQL 15 added regexp_count, regexp_instr, regexp_like and regexp_substr; MySQL 8 offers REGEXP_LIKE, REGEXP_SUBSTR and REGEXP_REPLACE (which replaces all matches by default).
A regex condition can't use a normal B-tree index, so on a large table it's a full scan. PostgreSQL's pg_trgm GIN indexes can speed up many regex searches, and for repeated use it's often better to extract the value once into its own indexed column. Regex is also slower than simple string functions, so prefer LIKE or SPLIT_PART when they're enough.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
UPDATE customersSET phone = regexp_replace(phone, '[^0-9]', '', 'g')WHERE phone ~ '[^0-9]';PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command response
Note: Three rows are an illustrative affected-row count. The actual PostgreSQL response is UPDATE n, where n is the number of customer rows containing a non-digit.
Key takeaway: Use 'g' for global replace; extract hot values into columns.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Try simpler tools first
If LIKE, SPLIT_PART or REPLACE can do it, use them. Reach for regex when the pattern needs character classes or repetition.
LIKE 'ORD-%' vs ~ 'ORD-[0-9]{6}'
When to use it & trade-offs
What it is
Regular expressions match text against patterns far more precise than LIKE: digits, character classes, repetition and alternatives. PostgreSQL uses the operators ~ (match), ~* (case-insensitive) and !~, plus functions such as regexp_replace, regexp_match and regexp_split_to_table. MySQL 8 has REGEXP_LIKE, REGEXP_REPLACE and REGEXP_SUBSTR.
Why it matters: Validating formats (PIN codes, phone numbers), extracting order ids from free text and cleaning messy imports are everyday data tasks that LIKE can't handle. Regex in SQL keeps that work in the database, but it can be slow on large tables and dialects differ, which is worth knowing before relying on it.
When to reach for it
- Validating formats such as PIN codes and phone numbers
- Extracting ids and codes from free text
- Cleaning characters out of imported data
When to avoid or be careful
- Unanchored patterns for validation
- Regex filters on huge tables without an index strategy
- Over-complicated patterns where a simple function would do
LIKE vs regex vs string functions
Strengths: Simple; prefix patterns can use an index.
Watch out: No character classes or repetition.
Strengths: Very expressive.
Watch out: Harder to read; no B-tree index support; slower.
Strengths: Fast and readable.
Watch out: Only works when the structure is regular.
Interview signals & numbers to know
When this topic comes up
- “Extract the order number from the message”
- “Find invalid phone numbers”
- “Remove all non-digits”
- LIKE isn't enough
- Data cleaning
Benchmarks & rules of thumb
- ^ … $
- anchor the whole string
- 'g'
- replace every match in PostgreSQL
- PostgreSQL 15
- added regexp_count / regexp_substr
Common mistakes & follow-ups
Common interview mistakes
- Validating with '[0-9]{6}' (no anchors) and accepting values with extra characters.
- Calling regexp_replace without 'g' in PostgreSQL and replacing only the first match.
- Running regex filters over millions of rows on every request.
Likely interviewer follow-ups
- How would you find rows where a phone number contains anything other than digits?
- What's the difference between ~ and LIKE?
- How would you speed up a regex search on a large table?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Regular Expressions in SQL (REGEXP_MATCHES, REGEXP_REPLACE, ~) with hands-on SQL practice and interview Q&A.