Split column into multiple rows in Postgres

In Postgres 9.3+ use a LATERAL join. Minimal form:

SELECT token, flag
FROM   tbl, unnest(string_to_array(subject, ' ')) token
WHERE  flag = 2;

The comma in the FROM list is (almost) equivalent to CROSS JOIN, LATERAL is automatically assumed for set-returning functions (SRF) in the FROM list. Why “almost”? See:

The alias “token” for the derived table is also assumed as column alias for a single anonymous column, and we assumed distinct column names across the query. Equivalent, more verbose and less error-prone:

SELECT s.token, t.flag
FROM   tbl t
CROSS  JOIN LATERAL unnest(string_to_array(subject, ' ')) AS s(token)
WHERE  t.flag = 2;

Or move the SRF to the SELECT list, which is allowed in Postgres (but not in standard SQL), to the same effect:

SELECT unnest(string_to_array(subject, ' ')) AS token, flag
FROM   tbl
WHERE  flag = 2;

The last one seems acceptable since SRF in the SELECT list have been sanitized in Postgres 10. See:

If unnest() does not return any rows (empty or NULL subject), the (implicit) join eliminates the row from the result. Use LEFT JOIN ... ON true to keep qualifying rows from tbl. See:

We could also use regexp_split_to_table(), but that’s typically slower because regular expressions cost a bit more. See:

Leave a Comment