Sub topic 7
Expanding JSON arrays into rows
This chapter assumes you can write CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true queries, as covered earlier in this tutorial. It also assumes you know the basic jsonb operators -> and ->>.
A jsonb column often holds an array, such as the line items of an order or the tags of a post. SQL can't filter, group, or join on array elements until they are rows. A set-returning function in FROM, combined with a lateral reference to the outer row, turns each array into rows.
Sample data
The examples use one table. Run this first so every query below works as written.
CREATE TABLE orders (
id int PRIMARY KEY,
customer text NOT NULL,
items jsonb
);
INSERT INTO orders (id, customer, items) VALUES
(1, 'ada', '[{"sku":"A-1","qty":2,"price":9.50},{"sku":"B-7","qty":1,"price":20}]'),
(2, 'bo', '[]'),
(3, 'cy', NULL),
(4, 'di', '[{"sku":"A-1","qty":5,"price":9.50,"tags":["gift","fragile"]}]');Order 2 has an empty array, order 3 has an SQL NULL, and only order 4 has a nested tags array. These edge cases drive most of the chapter.
The working model
jsonb_array_elements(jsonb) takes one array and returns one row per element. Each row has a single jsonb column named value. Because the function's argument is a column of the outer table, the function must run once per outer row. That is the same per-row evaluation you saw with lateral subqueries.
SELECT o.id, i.item ->> 'sku' AS sku, (i.item ->> 'qty')::int AS qty
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i(item);The result has three rows: (1, A-1, 2), (1, B-7, 1) and (4, A-1, 5). Orders 2 and 3 do not appear, because the function returned zero rows for them and a cross join with zero rows produces nothing.
Is the LATERAL keyword required here?
For a function call in FROM, LATERAL is optional. PostgreSQL treats a function that references earlier FROM items as lateral automatically. These three forms are equivalent:
SELECT o.id, i.item ->> 'sku' AS sku
FROM orders o CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i(item);
SELECT o.id, i.item ->> 'sku' AS sku
FROM orders o JOIN LATERAL jsonb_array_elements(o.items) AS i(item) ON true;
SELECT o.id, i.item ->> 'sku' AS sku
FROM orders o, jsonb_array_elements(o.items) AS i(item);Write LATERAL anyway. It shows the reader that the right side depends on the left, and it lets you switch to LEFT JOIN LATERAL without restructuring. The comma form is also risky in larger queries. An explicit JOIN binds tighter than a comma, so FROM a, b JOIN c ON ... cannot let the ON condition see a. Explicit join syntax avoids that.
Reading fields out of each element
jsonb_array_elements returns each element as jsonb. You then pull fields out with operators.
->returnsjsonb, which is useful when the field is itself an object or array.->>returnstext, which is what you want for scalars.- Casts convert text to a typed value.
If an element lacks a key, ->> returns NULL rather than an error. A typo such as 'quantity' therefore silently produces a column of NULLs. A wrong value that cannot be cast, such as "qty": "many", fails the whole query at the cast.
Naming the output columns
AS i(item) renames the default value column to item. You can omit the column list and write i.value, but a named column reads better. For jsonb_array_elements the alias list has exactly one column.
Typed columns with jsonb_to_recordset
When every element is an object with known keys, repeated ->> and casts get noisy. jsonb_to_recordset takes the array and a column definition list, and returns typed columns directly.
SELECT o.id, i.sku, i.qty, i.price, i.qty * i.price AS line_total
FROM orders o
CROSS JOIN LATERAL jsonb_to_recordset(o.items)
AS i(sku text, qty int, price numeric)
ORDER BY o.id, i.sku;Keys that are not listed, such as tags, are ignored. Listed keys that are missing become NULL. A value that cannot convert to the declared type raises an error, just like a cast. The column definition list is required, because the function returns record and PostgreSQL needs the types at plan time.
This is the clearest form when you need several typed fields. Use jsonb_array_elements when elements are scalars, when shapes vary, or when you want to keep the raw element for later steps.
Arrays of scalars
For ["gift","fragile"], jsonb_array_elements_text returns text directly, with no ->> step.
SELECT o.id, t.tag
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements_text(o.items -> 0 -> 'tags') AS t(tag);This returns two rows for order 4. The path o.items -> 0 -> 'tags' yields NULL for the other orders, which produces zero rows. For real data you usually expand the items first and then the tags, as the next sections show.
Keeping the position with WITH ORDINALITY
JSON arrays are ordered, and sometimes the position matters. Add WITH ORDINALITY to number the rows.
SELECT o.id, i.pos, i.item ->> 'sku' AS sku
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.items) WITH ORDINALITY AS i(item, pos)
ORDER BY o.id, i.pos;pos is a bigint that starts at 1 and restarts for each outer row. The alias list now has two names: the element, then the ordinality. Without ORDER BY, PostgreSQL does not promise that rows come back in array order, even though the function emits them in order. Sort by pos whenever order matters.
Empty arrays, NULLs and LEFT JOIN LATERAL
The first query in this chapter dropped orders 2 and 3. If you need one result row per order, such as for a report listing all orders, use LEFT JOIN LATERAL ... ON true.
SELECT o.id, i.sku, i.qty
FROM orders o
LEFT JOIN LATERAL jsonb_to_recordset(o.items)
AS i(sku text, qty int, price numeric) ON true
ORDER BY o.id, i.sku;Orders 2 and 3 now appear once each, with NULL in sku and qty. The functions in this chapter are strict, so a NULL array argument returns zero rows instead of raising an error.
Aggregation shows why this matters. A total over an order with no items should be 0, not a missing row:
SELECT o.id, coalesce(sum(i.qty * i.price), 0) AS total
FROM orders o
LEFT JOIN LATERAL jsonb_to_recordset(o.items)
AS i(sku text, qty int, price numeric) ON true
GROUP BY o.id
ORDER BY o.id;Order 1 totals 39.00, order 4 totals 47.50, and orders 2 and 3 total 0. With a CROSS JOIN, orders 2 and 3 would be missing from the report.
Nested arrays: chain the laterals
Each lateral item can reference any item to its left, so you can expand one level at a time. This query lists every tag on every item and keeps items that have no tags.
SELECT o.id, i.item ->> 'sku' AS sku, t.tag
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i(item)
LEFT JOIN LATERAL jsonb_array_elements_text(i.item -> 'tags') AS t(tag) ON true
ORDER BY o.id, sku, t.tag;The result is (1, A-1, NULL), (1, B-7, NULL), (4, A-1, fragile) and (4, A-1, gift). The first join is a cross join because orders without items are not interesting here. The second is a left join because an item without tags should still appear. Choose the join type separately at each level.
Errors on malformed data
Real JSON columns drift. Someone stores an object where an array was expected, or the JSON value null (different from SQL NULL). The element functions then raise errors instead of returning no rows.
| Input value | Result of `jsonb_array_elements` |
|---|---|
| SQL `NULL` | zero rows |
| `[]` | zero rows |
| `[1, 2]` | two rows |
| `{"a": 1}` | error: `cannot extract elements from an object` |
| JSON `null`, `5`, or `"x"` | error: `cannot extract elements from a scalar` |
One bad row fails the entire query. You can guard against this by checking the type before calling the function. Put the check in a CASE inside the argument, not in WHERE. PostgreSQL does not promise that a WHERE condition on the outer table runs before the lateral function does.
SELECT o.id, i.item ->> 'sku' AS sku
FROM orders o
LEFT JOIN LATERAL jsonb_array_elements(
CASE WHEN jsonb_typeof(o.items) = 'array' THEN o.items ELSE '[]'::jsonb END
) AS i(item) ON true;This treats any non-array value as an empty array. Decide deliberately whether that is right. Silently hiding malformed rows can mask a data bug, and you may prefer to find them with a separate query on jsonb_typeof(items) <> 'array'.
json versus jsonb
The matching functions for the json type are json_array_elements, json_array_elements_text and json_to_recordset. They behave the same way at the SQL level. A json value is stored as text and re-parsed on each access, while jsonb is stored in a binary form. For columns you query often, use jsonb. json is only worth keeping when you must preserve key order, duplicate keys, or exact whitespace.
Performance and filtering
Expansion costs work proportional to the total number of array elements, and it changes how the planner sees the data.
- Filter before you expand. If you only want orders containing a given sku, test the whole document first with containment, then expand the survivors. A GIN index supports the
@>operator:
```sql CREATE INDEX ordersitemsgin ON orders USING gin (items jsonbpathops);
SELECT o.id, i.item ->> 'sku' AS sku, (i.item ->> 'qty')::int AS qty FROM orders o CROSS JOIN LATERAL jsonbarrayelements(o.items) AS i(item) WHERE o.items @> '[{"sku":"A-1"}]' AND i.item ->> 'sku' = 'A-1'; ```
The first condition narrows orders through the index. The second keeps only the matching elements after expansion. A condition on i.item alone cannot use the GIN index, because the index covers the stored column, not the expanded rows.
- Expect poor row estimates. The planner does not know how long each array is. It uses a fixed row estimate for the function, so the estimated and actual row counts can differ a lot in
EXPLAIN (ANALYZE). Compare them before trusting a plan.
- Consider a real table for hot data. If you filter, join, or aggregate on the same array elements all the time, an
order_itemstable with ordinary columns and indexes will beat repeated expansion. JSON expansion fits occasional reporting and flexible documents better than core relational access.
Quick reference
| Goal | Function |
|---|---|
| Elements as `jsonb` | `jsonb_array_elements(arr)` |
| Elements as `text` | `jsonb_array_elements_text(arr)` |
| Typed columns from an array of objects | `jsonb_to_recordset(arr) AS x(col type, ...)` |
| Add a 1-based position | append `WITH ORDINALITY AS x(item, pos)` |
| Keep rows with empty or `NULL` arrays | `LEFT JOIN LATERAL ... ON true` |
Exercise
Using the sample data, write a query that returns each sku with the total quantity ordered across all orders, largest total first. Which join type should you use, and why?
Show answer
SELECT i.sku, sum(i.qty) AS totalqty FROM orders o CROSS JOIN LATERAL jsonbtorecordset(o.items) AS i(sku text, qty int) GROUP BY i.sku ORDER BY totalqty DESC; The result is A-1 with 7 and B-7 with 1. Use CROSS JOIN LATERAL because orders without items have no sku to group on, so keeping them with LEFT JOIN would only add a NULL group.
Exercise
A teammate writes (i.item ->> 'qty'::int) and gets the error invalid input syntax for type integer: "qty". Explain the cause and give the fix. Then explain what happens if one row stores items as the object {"sku":"X"} instead of an array.
Show answer
The :: cast binds tighter than ->>, so 'qty' is cast to int before the operator runs. The fix is (i.item ->> 'qty')::int. For the object value, jsonbarrayelements raises "cannot extract elements from an object", and the whole query fails. Guard against it with CASE WHEN jsonbtypeof(o.items) = 'array' THEN o.items ELSE '[]'::jsonb END inside the function argument, or find bad rows first with a query on jsonbtypeof(items) <> 'array'.