Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 37/ 160
02. Aggregations, Functions & Data Manipulation

Regular Expressions in SQL (REGEXP_MATCHES, REGEXP_REPLACE, ~)

Match and rewrite text with SQL regex operators when LIKE is not enough.

Advanced~ / ~* · REGEXP_REPLACE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Finding badly formatted phone numbersQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  phone4FROM5  customers6WHERE7  phone !~ '^[6-9][0-9]{9}$';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative invalid phone rows3 sample rows
Representative invalid phone rows
idphone
42+91 9876543210
585123456789
7198765-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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Keeping only digitsQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE customers2SET3  phone = regexp_replace(phone, '[^0-9]', '', 'g')4WHERE5  phone ~ '[^0-9]';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command response
UPDATE 3

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use 'g' for global replace; extract hot values into columns.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Choice

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.

Focus at this step

LIKE 'ORD-%' vs ~ 'ORD-[0-9]{6}'

What to watch at this step
Simplest
that works
Tip: use ← → to move between steps

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

LIKE / ILIKE
Best for: Simple starts-with, ends-with, contains

Strengths: Simple; prefix patterns can use an index.

Watch out: No character classes or repetition.

Regular expressions
Best for: Format validation, complex extraction and cleanup

Strengths: Very expressive.

Watch out: Harder to read; no B-tree index support; slower.

SPLIT_PART / SUBSTRING / REPLACE
Best for: Fixed-delimiter splitting and simple replacements

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?
Interview tip: Show one validation (anchored) and one extraction example, and mention the 'g' flag and performance. It shows practical use, not just syntax.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Generating Series & Synthetic Data (GENERATE_SERIES)
Next topic
Set Operations (UNION vs UNION ALL)