← Back to SQL, page 6

sql-0111 · Hard senior

Write a query that splits a comma-separated string such as 'sql,joins,cte' into one row per value.

In SQLite, a recursive CTE can peel off one item at a time with instr and substr until the string is empty. PostgreSQL has string_to_table (or unnest(string_to_array(...))) for this. Storing lists in one column is usually a design smell; splitting is mostly needed to clean imported data.

Full answer

SQLite has no built-in split function, so a recursive CTE takes the string apart piece by piece. Each step keeps the first item and passes the rest on:

sql
WITH RECURSIVE parts(item, rest) AS (
  SELECT NULL, 'sql,joins,cte' || ','
  UNION ALL
  SELECT substr(rest, 1, instr(rest, ',') - 1),
         substr(rest, instr(rest, ',') + 1)
  FROM parts
  WHERE rest <> ''
)
SELECT item FROM parts WHERE item IS NOT NULL;
item
sql
joins
cte

How it works: rest always has a trailing comma appended, so instr(rest, ',') finds the end of the next item. substr before the comma is the item; substr after it is what remains. The recursion stops when nothing remains.

PostgreSQL does the same in one function call:

sql
SELECT string_to_table('sql,joins,cte', ',') AS item;
item
sql
joins
cte

SQLite's JSON functions offer another route if the string can be turned into a JSON array:

sql
SELECT value AS item
FROM json_each('["' || replace('sql,joins,cte', ',', '","') || '"]')
ORDER BY key;
item
sql
joins
cte

If a column regularly holds comma-separated values, that usually means a missing child table (one row per tag). Splitting is a one-time repair step on the way to that design, not something to run in every query.

sql
WITH RECURSIVE parts(item, rest) AS (
  SELECT NULL, 'sql,joins,cte' || ','
  UNION ALL
  SELECT substr(rest, 1, instr(rest, ',') - 1),
         substr(rest, instr(rest, ',') + 1)
  FROM parts
  WHERE rest <> ''
)
SELECT item FROM parts WHERE item IS NOT NULL;

SELECT value AS item
FROM json_each('["' || replace('sql,joins,cte', ',', '","') || '"]')
ORDER BY key;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • A recursive CTE can split strings in SQLite
  • Each step emits one item and passes the remainder
  • PostgreSQL has string_to_table and string_to_array
  • Comma-separated columns usually mean a missing child table

Common mistakes

  • Forgetting the trailing delimiter and losing the last item
  • Keeping lists in a column and splitting them in every query

Follow-ups

  • How would you count how many items each row's list contains?
  • How would you turn the split values into rows of a tags table?

Tips

  • Recommend the schema fix after showing the split