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 29/ 160
02. Aggregations, Functions & Data Manipulation

String Splitting & Pattern Extraction (SPLIT_PART, POSITION, LENGTH)

Split delimited strings and locate substrings for light parsing in SQL.

IntermediateSPLIT_PART · POSITION3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Splitting cuts text at a separator, like '@' or ',', so you can use each piece on its own.

Think of it like…

Reading an address label: the first line is the name, the part after the comma is the city, the last part is the PIN code. Splitting tells the database where each part starts and ends.

Where you’ve seen it

Orders per email domain: SELECT SPLIT_PART(email, '@', 2) AS domain, COUNT(*) FROM customers GROUP BY 1 ORDER BY 2 DESC; and turning a tags column into rows: SELECT p.id, TRIM(t.tag) FROM products p CROSS JOIN LATERAL unnest(string_to_array(p.tags, ',')) AS t(tag);

Words you’ll hear

SPLIT_PART
PostgreSQL / Snowflake: the nth piece after splitting on a delimiter.
SUBSTRING_INDEX
MySQL: everything before (positive count) or after (negative count) the nth delimiter.
string_to_array + unnest
PostgreSQL: split into an array, then expand into rows.
STRING_SPLIT
SQL Server: a table of pieces, one row each.

Visual diagram

Loading interactive diagram

Theory & example queries

Extracting a piece

SPLIT_PART splits on a fixed delimiter and returns one piece by position, starting at 1; if the piece doesn't exist it returns an empty string, not NULL. Since PostgreSQL 14, a negative position counts from the end (SPLIT_PART(path, '/', -1) is the file name). MySQL's SUBSTRING_INDEX(str, delim, n) returns everything before the nth delimiter, and with a negative n everything after it counting from the right; combine two calls to get a middle piece.

For variable formats, POSITION('@' IN email) or STRPOS(email, '@') finds where a character is, and SUBSTRING takes the text around it. When the format is irregular, a regular expression (regexp_match) is often clearer.

Pieces of a URLQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  SPLIT_PART(SPLIT_PART(url, '://', 2), '/', 1) AS host,3  SPLIT_PART(url, '/', -1) AS last_segment4FROM5  page_views;
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/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Extracted URL components3 sample rows
Extracted URL components
hostlast_segment
docs.example.comwindows
shop.example.comcheckout
blog.example.comsql

Note: Assumes these page_views URL patterns; negative SPLIT_PART positions require PostgreSQL 14+.

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

(negative positions need PostgreSQL 14+).

Key takeaway: SPLIT_PART for fixed delimiters; regex for irregular formats.

Turning a list into rows

To analyse each item in a delimited list, expand it into rows: in PostgreSQL, unnest(string_to_array(tags, ',')) (or regexp_split_to_table for complex delimiters), joined with CROSS JOIN LATERAL so each product's tags stay attached to it. Add WITH ORDINALITY to keep each item's position. In SQL Server, CROSS APPLY STRING_SPLIT(tags, ','); in MySQL 8, use JSON_TABLE or a recursive CTE.

Always TRIM the pieces and decide what to do with empty items (from trailing or doubled commas). If you're splitting the same column in many queries, that's a sign the data should be normalised into a child table with one row per item.

Tag counts across productsQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  LOWER(TRIM(t.tag)) AS tag,3  COUNT(*)4FROM5  products p6  CROSS JOIN LATERAL unnest(string_to_array(p.tags, ',')) AS t (tag)7WHERE8  TRIM(t.tag) <> ''9GROUP BY10  111ORDER BY12  2 DESC;
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/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Normalized tag counts3 sample rows
Normalized tag counts
tagcount
sql14
postgres9
indexes5

Note: Assumes comma-separated values and trimmed, case-insensitive tags; empty pieces are excluded.

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

Key takeaway: unnest + LATERAL turns lists into rows; trim and drop empties.

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 1Profiling

Inspect the format

Look at real values for the delimiter, extra spaces, missing parts and inconsistent formats.

Focus at this step

'a,b' · 'a, b' · 'a,,b' · ''

What to watch at this step
Find
edge cases
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Splitting pulls structured pieces out of text. PostgreSQL's SPLIT_PART(text, delimiter, n) returns the nth piece (SPLIT_PART('asha@x.com', '@', 2) is 'x.com'); POSITION / STRPOS find where a substring starts; string_to_array + unnest turns a delimited list into rows. MySQL uses SUBSTRING_INDEX, and SQL Server uses STRING_SPLIT and CHARINDEX.

Why it matters: Emails, product codes, file paths, URLs and comma-separated imports all hide useful fields inside text. Extracting them in SQL is common in cleaning and analytics work, and "split this comma-separated column into rows" is a classic interview task.

When to reach for it

  • Email domains, URL hosts and file extensions
  • Codes with structured parts (IN-MH-2026-001)
  • Expanding comma-separated imports into rows

When to avoid or be careful

  • Splitting the same column in every query instead of normalising
  • Forgetting to TRIM pieces
  • Assuming a missing piece returns NULL

Splitting functions across databases

PostgreSQL: SPLIT_PART, string_to_array, unnest
Best for: Pieces by position, and lists into rows

Strengths: Simple; negative positions from version 14.

Watch out: Missing pieces return '' rather than NULL.

MySQL: SUBSTRING_INDEX
Best for: Everything before or after the nth delimiter

Strengths: One function covers both directions.

Watch out: Middle pieces need nested calls; no built-in split-to-rows.

SQL Server: STRING_SPLIT, CHARINDEX
Best for: Lists into rows with CROSS APPLY

Strengths: Table-valued output.

Watch out: Ordinal column only from SQL Server 2022.

Interview signals & numbers to know

When this topic comes up

  • “Extract the domain from the email”
  • “Split this comma-separated column into rows”
  • Parsing codes and paths
  • Data cleaning
  • Denormalised imports

Benchmarks & rules of thumb

1 -
first piece position in SPLIT_PART
'' -
result for a piece that doesn't exist
PostgreSQL 14 -
negative SPLIT_PART positions

Common mistakes & follow-ups

Common interview mistakes

  • Grouping by SPLIT_PART(tags, ',', 2) without TRIM, so ' summer' and 'summer' are different.
  • Expecting NULL for missing pieces and getting empty strings that pass IS NOT NULL checks.
  • Writing nested SUBSTRING_INDEX calls in MySQL when a JSON_TABLE or recursive CTE would be clearer.

Likely interviewer follow-ups

  • How would you count products per tag when tags are stored as 'a,b,c'?
  • How would you get the file extension from a path?
  • Why might you normalise a delimited column instead of splitting it in queries?
Interview tip: Show one column extraction (email domain) and one list-to-rows expansion (tags), and mention trimming and normalising. That's the full picture in two queries.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply String Splitting & Pattern Extraction (SPLIT_PART, POSITION, LENGTH) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
String Functions (CONCAT, SUBSTRING, TRIM, UPPER, LOWER, REPLACE)
Next topic
Numeric & Math Functions (ROUND, CEIL, FLOOR, ABS, MOD, POWER)