Sub topic 7
Expanding JSON Arrays into Rows
Assume you know SELECT, joins, table aliases, and basic JSONB operators. This chapter uses PostgreSQL's jsonb type. A jsonb value stores JSON in a form that PostgreSQL can query efficiently.
A JSON array stores an ordered list. For example, an order might store its line items in one column:
[
{"sku": "BOOK-1", "qty": 2},
{"sku": "PEN-2", "qty": 5}
]Relational queries usually work best when each item is a separate row. PostgreSQL provides the set-returning function jsonb_array_elements for this conversion. A set-returning function is a function that produces zero or more rows.
Expand one array for each row
The following example creates temporary data so that the complete query can run as shown:
CREATE TEMP TABLE orders (
id integer,
customer_id integer,
items jsonb
);
INSERT INTO orders (id, customer_id, items) VALUES
(101, 7, '[{"sku":"BOOK-1","qty":2},{"sku":"PEN-2","qty":5}]'),
(102, 8, '[{"sku":"MUG-3","qty":1}]');
SELECT
o.id AS order_id,
i.item_no,
i.item ->> 'sku' AS sku,
(i.item ->> 'qty')::integer AS quantity
FROM orders AS o
CROSS JOIN LATERAL jsonb_array_elements(o.items)
WITH ORDINALITY AS i(item, item_no)
ORDER BY o.id, i.item_no;The expression o.items refers to the current row from orders. The LATERAL keyword allows the function on the right side to use that earlier table. PostgreSQL evaluates the function separately for each order.
WITH ORDINALITY adds a counter beginning at 1. The alias i(item, item_no) names the JSON value and its counter.
The result is:
| order_id | item_no | sku | quantity |
|---|---|---|---|
| 101 | 1 | BOOK-1 | 2 |
| 101 | 2 | PEN-2 | 5 |
| 102 | 1 | MUG-3 | 1 |
The ->> operator extracts a JSON field as text. The cast to integer changes that text into a number that you can use in arithmetic or comparisons. The -> operator keeps the result as JSONB.
| Expression | Result type | Example |
|---|---|---|
| `item -> 'qty'` | `jsonb` | `5` |
| `item ->> 'qty'` | `text` | `5` |
| `(item ->> 'qty')::integer` | `integer` | `5` |
Why LATERAL matters
jsonb_array_elements needs a different input for every order. Without a per-row evaluation rule, PostgreSQL would have no way to connect each function call to the correct orders row.
The query has this logical shape:
orders row
|
+-- items array
|
+-- item 1
+-- item 2
+-- item 3CROSS JOIN LATERAL returns one result row for every array element. If the array is empty, the order contributes no result rows. This is useful when you only want orders that contain items.
A function in FROM can often reference preceding tables even without writing LATERAL, but writing it explicitly documents the dependency and makes the query's intent clear.
Keep orders with empty arrays
Use LEFT JOIN LATERAL when the parent row must remain in the result even if its array has no elements:
SELECT
o.id AS order_id,
i.item_no,
i.item ->> 'sku' AS sku,
(i.item ->> 'qty')::integer AS quantity
FROM orders AS o
LEFT JOIN LATERAL jsonb_array_elements(
COALESCE(o.items, '[]'::jsonb)
) WITH ORDINALITY AS i(item, item_no)
ON true
ORDER BY o.id, i.item_no;COALESCE replaces a SQL NULL with an empty JSON array. The condition ON true means that the lateral function controls whether a match exists. With a left join, an order without elements stays in the result, with NULL values for the item columns.
Use a filter inside the lateral query when you want to expand and filter at the same time:
SELECT o.id AS order_id, i.item ->> 'sku' AS sku
FROM orders AS o
CROSS JOIN LATERAL jsonb_array_elements(o.items) AS i(item)
WHERE (i.item ->> 'qty')::integer >= 2;The function must receive an array. Passing a JSON object, string, or malformed value can produce an error. If the column can contain different JSON shapes, validate the data or normalize it before expansion.
Exercise
Write a query that keeps every order, expands its items array, and returns the order ID, array position, and SKU. Treat a NULL items value as an empty array.
Show answer
Use LEFT JOIN LATERAL with COALESCE:
SELECT o.id, i.itemno, i.item ->> 'sku' AS sku FROM orders AS o LEFT JOIN LATERAL jsonbarrayelements( COALESCE(o.items, '[]'::jsonb) ) WITH ORDINALITY AS i(item, itemno) ON true ORDER BY o.id, i.item_no;