Knowledge base / SQL
UNNEST in PostgreSQL: arrays, rows and missing elements
I explain positional pairing versus an array cross product and show how to preserve a parent record whose array has no elements.

When an order contains an array of products, I sometimes need one row per product. PostgreSQL’s unnest provides that expansion. I immediately check two things: what happens to an empty array, and whether the expanded result still counts orders or now counts their elements. The second distinction can change a report total without producing any syntax error.
These synthetic examples concern one-dimensional arrays in PostgreSQL 18. Do not transfer their syntax automatically to BigQuery or another engine. This entry expands native PostgreSQL arrays rather than arbitrary JSON documents or comma-separated text. Identifying the input type is part of choosing the operation.
One array and an element sequence number
The array documentation describes unnest as returning rows from array elements. I add WITH ORDINALITY for presentation, then specify the final ordering with ORDER BY.
SELECT u.pos, u.item
FROM unnest(ARRAY['book', 'pen', 'book'])
WITH ORDINALITY AS u(item, pos)
ORDER BY u.pos;
The expected pairs are (1, book), (2, pen) and (3, book). The duplicate remains. This operation does not turn the list into a collection of unique product names. If distinct names are required, make a separate decision about removing repetitions rather than assuming expansion also performs deduplication.
Ordinality numbers output rows starting at 1. It is an expansion sequence number, rather than a guarantee of the array’s original subscript. PostgreSQL permits other lower bounds. If you need the actual subscripts, investigate generate_subscripts. Here I use ordinary arrays created with the ARRAY constructor.
Multiple arrays pair positions, even with unequal lengths
Multi-argument unnest in FROM pairs the first elements, then the second elements and so on. Shorter arrays are padded with NULL. The previous Polish entry incorrectly claimed that different lengths caused an error.
SELECT u.pos, u.item, u.qty
FROM unnest(ARRAY['book', 'pen'], ARRAY[2])
WITH ORDINALITY AS u(item, qty, pos)
ORDER BY u.pos;
| pos | item | qty |
|---|---|---|
| 1 | book | 2 |
| 2 | pen | NULL |
Successful execution does not make the record complete. I would not replace the missing quantity with zero without agreeing its meaning. If products and quantities must form complete pairs, check their counts before analysing them. Ordering matters as well: two arrays of equal length can still contain incorrectly matched information. Positional pairing follows the input arrangement rather than discovering a business relationship.
Do not replace this with two independent CROSS JOIN unnest(...) operations. Two arrays of two elements then produce four combinations instead of two positional pairs. That is useful when all combinations are intended. For a price list or order items, it would usually answer a different question and could multiply values unexpectedly.
Expanding a column changes record counts
This example includes an order with two products, an empty array, an unknown array and an array containing one NULL element. The text[] cast makes the element type explicit for empty input.
WITH orders(id, items) AS (
VALUES
(1, ARRAY['book', 'pen']::text[]),
(2, ARRAY[]::text[]),
(3, NULL::text[]),
(4, ARRAY[NULL]::text[])
)
SELECT o.id, u.pos, u.item
FROM orders AS o
CROSS JOIN LATERAL unnest(o.items)
WITH ORDINALITY AS u(item, pos)
ORDER BY o.id, u.pos;
The result has three rows: (1, 1, book), (1, 2, pen) and (4, 1, NULL). Orders 2 and 3 supply no element for expansion. Order 4 does contain an element, whose value is unknown. Those situations should not collapse into one unexplained category labelled missing. They reflect different input states and may require different actions in a data-quality report.
LATERAL is optional for functions in FROM: a function can reference an earlier FROM item without the keyword. I write it explicitly to make the dependence on o.items readable. Referring to a column does not itself make that keyword mandatory in this syntax.

LEFT JOIN preserves a parent without an element
If the result must also list orders without products, use a left join. The sample remains the same; the decision about preserving parent records changes.
WITH orders(id, items) AS (
VALUES
(1, ARRAY['book', 'pen']::text[]),
(2, ARRAY[]::text[]),
(3, NULL::text[]),
(4, ARRAY[NULL]::text[])
)
SELECT o.id, u.pos, u.item
FROM orders AS o
LEFT JOIN LATERAL unnest(o.items)
WITH ORDINALITY AS u(item, pos) ON true
ORDER BY o.id, u.pos;
| id | pos | item |
|---|---|---|
| 1 | 1 | book |
| 1 | 2 | pen |
| 2 | NULL | NULL |
| 3 | NULL | NULL |
| 4 | 1 | NULL |
Ordinality distinguishes the NULL element in order 4 from the rows supplied by the join for orders 2 and 3. The expansion columns alone do not distinguish an empty array from an unknown array. Keep the source column or a separate input status if the report needs that distinction. Preserving a row is not the same as preserving every fact about its original input.
What I avoid summing after expansion
If order 1 has an amount of 100, its two expanded products repeat that amount twice. Summing at the element level gives 200. This comes from row multiplication, rather than extra sales. Aggregate order amounts at the order level or explicitly design a rule for allocating the amount across items. The correct choice depends on the business question.
Similarly, COUNT(*) after the left join also counts preserved rows without an element. Our result has five rows, four orders and three actual array elements. Two elements have known names. Choose the count according to which of those things you need to describe. A column called count is not a sufficiently clear definition when several valid counts coexist in the same expanded table.
Exercise: change one input
Add book to the array for order 2 and predict both results. The CROSS JOIN version gains one row. The LEFT JOIN version still has five rows, but ID 2 now has position 1 and a product name. This is a useful way to check whether you understand parent preservation rather than only the basic expansion syntax.
Before applying the operation, establish the result level, NULL meaning and rule for incompatible lists. The LEFT JOIN guide revisits record preservation, while the SQL knowledge base links related entries. I make no speed promise here: resulting row counts and execution plans require assessment for the particular dataset and query.
Key takeaways
Do unequal array lengths cause an UNNEST error?
PostgreSQL pads shorter arrays with NULL in multi-argument UNNEST in FROM. This does not establish that the data is correctly paired.
Is LATERAL mandatory when unnesting a column?
For functions in PostgreSQL's FROM clause, LATERAL is optional. I write it explicitly to make the reference to an earlier FROM item visible.
How do I preserve a record with an empty array?
Use LEFT JOIN LATERAL with ON true. Expansion columns become NULL; ordinality distinguishes the absence of an element from an actual NULL element.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
