String Splitting & Pattern Extraction (SPLIT_PART, POSITION, LENGTH)
Split delimited strings and locate substrings for light parsing in SQL.
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
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.
SELECT SPLIT_PART(SPLIT_PART(url, '://', 2), '/', 1) AS host, SPLIT_PART(url, '/', -1) AS last_segmentFROM page_views;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Extracted URL components3 sample rows
| host | last_segment |
|---|---|
| docs.example.com | windows |
| shop.example.com | checkout |
| blog.example.com | sql |
Note: Assumes these page_views URL patterns; negative SPLIT_PART positions require PostgreSQL 14+.
(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.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT LOWER(TRIM(t.tag)) AS tag, COUNT(*)FROM products p CROSS JOIN LATERAL unnest(string_to_array(p.tags, ',')) AS t (tag)WHERE TRIM(t.tag) <> ''GROUP BY 1ORDER BY 2 DESC;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Normalized tag counts3 sample rows
| tag | count |
|---|---|
| sql | 14 |
| postgres | 9 |
| indexes | 5 |
Note: Assumes comma-separated values and trimmed, case-insensitive tags; empty pieces are excluded.
Key takeaway: unnest + LATERAL turns lists into rows; trim and drop empties.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Inspect the format
Look at real values for the delimiter, extra spaces, missing parts and inconsistent formats.
'a,b' · 'a, b' · 'a,,b' · ''
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
Strengths: Simple; negative positions from version 14.
Watch out: Missing pieces return '' rather than NULL.
Strengths: One function covers both directions.
Watch out: Middle pieces need nested calls; no built-in split-to-rows.
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?
Knowledge check
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.