Sub topic 3
Expanding JSON arrays into rows
This chapter assumes you know basic SELECT, joins, subqueries in FROM, and table aliases. It builds on the LATERAL basics from earlier chapters.
A set-returning function such as jsonb_array_elements returns many rows for each input row. Placed after a lateral reference, it turns each JSON array into one row per element.
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);Each order contributes one row per line item. The ->> operator reads a key as text, and the cast converts it to an integer.
Computing a value once and reusing it
A lateral subquery can compute an expression once per row. Other columns in the select list can then refer to that result by name, which avoids repeating the expression.
SELECT o.id, n.net, o.gross - n.net AS tax
FROM orders o
CROSS JOIN LATERAL (SELECT o.gross / 1.2 AS net) AS n;Which joins allow LATERAL references
A LATERAL item can refer to columns of items listed before it. CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true both support this. A RIGHT JOIN LATERAL or FULL JOIN LATERAL that refers to the left side fails with an "invalid reference" error. Rewrite such a query with LEFT JOIN LATERAL, or reverse the table order.
> Hmm, a callout explains this rule:
Performance, indexes and EXPLAIN
The lateral subquery runs once per outer row. For top-N queries, an index on the correlation column and the sort column lets each lookup read only the newest rows:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.id, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o;Look for an Index Scan on orders_customer_created_idx in the plan. A Seq Scan on orders repeated for every customer means the index is missing or unused.
When to use something other than LATERAL
Use a window function such as ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) when you need top-N rows for every group in one pass. A correlated scalar subquery fits when you need only one value per row. Expanding JSON arrays has no simple window-function equivalent, so LATERAL remains the clearest choice there.
Exercise
Why does CROSS JOIN LATERAL jsonb_array_elements(o.items) return one row per line item instead of one row per order?
Show answer
The function returns one row for each array element, and the lateral reference runs it once per order row, so the rows multiply.