← Back to PostgreSQL, page 3

postgresql-0049 · Medium mid

Expand parallel arrays into rows with unnest, keeping element positions with WITH ORDINALITY.

unnest(a, b) in FROM expands several arrays side by side, padding shorter ones with NULL. WITH ORDINALITY adds a column with each element's 1-based position, which preserves order for later sorting or for pairing values with their index. It works with any set-returning function, including jsonb_array_elements and regexp_split_to_table.

Full answer

Schema and sample rows:

sql
CREATE TABLE quizzes (student text, answers text[], marks int[]);
INSERT INTO quizzes VALUES ('Asha', ARRAY['b','c','a'], ARRAY[1,1,0]), ('Ben', ARRAY['a','c'], ARRAY[0,1,1]);
sql
SELECT q.student, u.pos, u.answer, u.mark FROM quizzes q CROSS JOIN LATERAL unnest(q.answers, q.marks) WITH ORDINALITY AS u(answer, mark, pos) ORDER BY q.student, u.pos;

Output:

text
 student | pos | answer | mark
---------+-----+--------+------
 Asha    | 1   | b      | 1
 Asha    | 2   | c      | 1
 Asha    | 3   | a      | 0
 Ben     | 1   | a      | 0
 Ben     | 2   | c      | 1
 Ben     | 3   | NULL   | 1
(6 rows)
sql
SELECT word, n FROM regexp_split_to_table('to be or not to be', ' ') WITH ORDINALITY AS t(word, n) WHERE word = 'be';

PostgreSQL returns:

text
 word | n
------+---
 be   | 2
 be   | 6
(2 rows)

Asha's arrays have equal lengths, so each position pairs an answer with its mark. Ben has two answers but three marks, so position 3 has a NULL answer, which shows a data problem worth checking. The ordinality column is listed last in the alias because it is appended after the function's own columns. The second query uses the same idea on a string split, reporting that 'be' is the second and sixth word. Relying on the output order of unnest without ORDINALITY works in practice but is not guaranteed after joins or sorting.

sql
CREATE TABLE quizzes (student text, answers text[], marks int[]);
INSERT INTO quizzes VALUES ('Asha', ARRAY['b','c','a'], ARRAY[1,1,0]), ('Ben', ARRAY['a','c'], ARRAY[0,1,1]);

SELECT q.student, u.pos, u.answer, u.mark FROM quizzes q CROSS JOIN LATERAL unnest(q.answers, q.marks) WITH ORDINALITY AS u(answer, mark, pos) ORDER BY q.student, u.pos;

SELECT word, n FROM regexp_split_to_table('to be or not to be', ' ') WITH ORDINALITY AS t(word, n) WHERE word = 'be';

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Multi-argument unnest zips arrays
  • Shorter arrays are padded with NULL
  • WITH ORDINALITY adds positions
  • The ordinality column comes last in the alias
  • Works with any set-returning function

Common mistakes

  • Relying on implicit element order
  • Unnesting arrays separately and getting a cross product

Follow-ups

  • How would you rebuild the arrays after editing elements?
  • What happens with unnest in the SELECT list?

Tips

  • Show the NULL padding