Sub topic 5
Turning arrays and objects into rows
This chapter assumes you can write joins and aggregates in SQL. It also assumes you know the orders table from the earlier chapters and the -> and ->> operators. If you ran the UPDATE examples from the modifying chapter, re-insert the original two documents so your results match the ones shown here.
A JSON array or object holds many values in one cell. SQL filters, joins, and aggregates work on rows. The set-returning functions in this chapter convert between the two shapes. Once a nested array is a set of rows, you can use WHERE, GROUP BY, and JOIN on it.
The function families
PostgreSQL has three groups of expansion functions. Each has a json_ version and a jsonb_ version. This chapter uses the jsonb_ ones.
| Function | Input | Output |
|---|---|---|
| `jsonb_array_elements(arr)` | array | one `jsonb` row per element |
| `jsonb_array_elements_text(arr)` | array | one `text` row per element |
| `jsonb_each(obj)` | object | rows of `key text, value jsonb` |
| `jsonb_each_text(obj)` | object | rows of `key text, value text` |
| `jsonb_object_keys(obj)` | object | one `text` row per top-level key |
| `jsonb_to_record(obj)` | object | one row with columns you declare |
| `jsonb_to_recordset(arr)` | array of objects | one row per element, with columns you declare |
The first group works on arrays, the second on objects, and the third maps JSON onto typed columns.
Expanding arrays
The standard pattern joins each parent row to the elements of one of its arrays.
SELECT o.id,
i ->> 'sku' AS sku,
(i ->> 'qty')::int AS qty
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i;With the two sample documents, the result has three rows:
id | sku | qty
----+-----+-----
1 | A1 | 2
1 | B7 | 1
2 | A1 | 1LATERAL lets the function on the right refer to the row o on the left. Without it, a function in FROM could not see columns of earlier tables. For functions, PostgreSQL treats the keyword as implied, so this shorter form is equivalent:
SELECT o.id, i ->> 'sku' AS sku
FROM orders o, jsonb_array_elements(o.details -> 'items') AS i;Write CROSS JOIN LATERAL anyway. It shows the dependency, and it makes it easy to switch to LEFT JOIN LATERAL when you need to (see the edge cases below).
Each element i is a jsonb value, so you read fields from it with the same operators as before. Cast the ->> result to a SQL type when you need to compare or sum it.
Scalar arrays and the _text variant
When the array holds scalars, such as ["red", "blue"], use jsonb_array_elements_text. It returns plain text, so you skip the #>> '{}' trick for unwrapping a string.
SELECT t.id, tag
FROM (VALUES (1, '["red", "blue"]'::jsonb),
(2, '["green"]'::jsonb)) AS t(id, tags)
CROSS JOIN LATERAL jsonb_array_elements_text(t.tags) AS tag;Without the _text variant, each tag would be a jsonb string and would print with double quotes.
Keeping the element position
JSON arrays are ordered, but a plain set of rows is not. WITH ORDINALITY adds a counter column that starts at 1.
SELECT o.id, i.pos, i.item ->> 'sku' AS sku
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items')
WITH ORDINALITY AS i(item, pos);The alias i(item, pos) names the value column first and the counter second. Use pos in an ORDER BY or in a window function whenever array order matters. Do not rely on rows coming out in array order unless you sort on it.
Aggregating over expanded rows
After expansion, ordinary aggregation applies. This query totals the units sold per SKU across all orders:
SELECT i ->> 'sku' AS sku,
sum((i ->> 'qty')::int) AS units
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i
GROUP BY 1
ORDER BY 1;The result is A1 with 3 units and B7 with 1.
Expanding objects
jsonb_each turns the top-level key/value pairs of an object into rows. It is useful when keys are data, such as a map of settings or a dictionary of counters, and you don't know them in advance.
SELECT key, value
FROM orders o
CROSS JOIN LATERAL jsonb_each(o.details -> 'shipping')
WHERE o.id = 1;For order 1 this returns one row: key city, value "Oslo". The value column is jsonb, so the string keeps its quotes. jsonb_each_text returns value as text, which prints Oslo and is easier to compare with ordinary strings.
To list the distinct top-level keys used across a table, call jsonb_object_keys in the select list:
SELECT DISTINCT jsonb_object_keys(details) AS key
FROM orders
ORDER BY key;With the sample data this returns items, shipping, status, and total. This query is a quick way to audit how consistent the documents in a column are.
jsonb_each expands only one level. A value that is itself an object or array comes back as a jsonb value, and you can expand it again in another lateral join.
Mapping JSON onto typed columns
Reading each field with ->> and a cast gets repetitive. jsonb_to_recordset does it in one step. You declare the column names and types, and PostgreSQL extracts the matching keys and converts them.
SELECT o.id, x.sku, x.qty
FROM orders o
CROSS JOIN LATERAL jsonb_to_recordset(o.details -> 'items')
AS x(sku text, qty int);This returns the same three rows as the first example in this chapter. It works with an array of objects. For a single object, use jsonb_to_record:
SELECT o.id, d.status, d.total
FROM orders o
CROSS JOIN LATERAL jsonb_to_record(o.details)
AS d(status text, total numeric);The matching rules are worth knowing:
- Keys that are not named in the column list are ignored.
- A declared column with no matching key gets SQL
NULL. - Key names are matched case-sensitively, so a column
Qtydoes not match the keyqtyunless you quote the identifier ("Qty"). - A value that cannot be converted to the declared type raises an error and aborts the query. For example,
"abc"declared asintfails. - A nested object or array declared as
jsonbstays asjsonb. Declared astext, it becomes its JSON text.
jsonb_populate_record and jsonb_populate_recordset work the same way, but take the column definitions from an existing table or composite type, as in jsonb_populate_recordset(null::my_type, doc). They are handy when a table already matches the document shape.
Edge cases and errors
Empty arrays and missing keys remove the parent row
CROSS JOIN LATERAL is an inner join. A parent row whose array is empty, or whose key is missing, produces no output rows at all. A missing key makes -> return SQL NULL, and these functions return zero rows for a NULL input.
When you want to keep the parent, use LEFT JOIN LATERAL ... ON true:
SELECT t.id, e
FROM (VALUES (1, '[10, 20]'::jsonb),
(2, '[]'::jsonb)) AS t(id, arr)
LEFT JOIN LATERAL jsonb_array_elements(t.arr) AS e ON true;The result is three rows: 1 | 10, 1 | 20, and 2 | NULL. The ON true is required syntax, because the lateral function already restricts which rows match.
The wrong JSON type raises an error
jsonb_array_elements accepts only an array. If one document in the table has an object, a string, or a JSON null where the array should be, the whole query fails with an error such as cannot extract elements from an object or cannot extract elements from a scalar. One bad row breaks the query for every row.
You might try a WHERE jsonb_typeof(...) = 'array' filter, but the planner is free to evaluate the function before the filter. Guard the argument itself instead:
SELECT o.id, i ->> 'sku' AS sku
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(
CASE WHEN jsonb_typeof(o.details -> 'items') = 'array'
THEN o.details -> 'items'
ELSE '[]'::jsonb
END
) AS i;The CASE runs inside the argument expression, so the function never sees a non-array. An alternative is jsonb_path_query(details, '$.items[*]'). In the default lax mode, a path query ignores missing keys and does not raise structural errors.
Expanding rows multiplies parent values
After an expansion join, each parent row appears once per element. Any parent column you aggregate is then counted once per element. Compare these two queries:
-- Wrong: Ada's total is counted twice, once per item.
SELECT sum((o.details ->> 'total')::numeric) AS revenue
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i;
-- Right: aggregate the parent rows before or without expanding.
SELECT sum((details ->> 'total')::numeric) AS revenue
FROM orders;The first query returns 95.00 (42.50 twice, plus 10.00). The second returns the correct 52.50. When you need both parent-level and element-level numbers, compute them in separate subqueries or CTEs and join the results.
Performance
Expansion functions run once per parent row and cannot use a GIN index on the expanded values. To find orders that contain a SKU, a containment filter is usually faster than expanding every document and filtering the result:
SELECT id FROM orders
WHERE details @> '{"items": [{"sku": "B7"}]}';Use expansion when you need the elements themselves as rows, such as for output, joins, and aggregation. Use containment when you only need to know whether a match exists. The indexing chapter covers the index side.
Folding rows back into JSON
Expansion has an inverse. After you filter or transform the rows, jsonb_agg builds an array again:
SELECT o.id,
jsonb_agg(i) FILTER (WHERE (i ->> 'qty')::int > 1) AS big_items
FROM orders o
CROSS JOIN LATERAL jsonb_array_elements(o.details -> 'items') AS i
GROUP BY o.id;Order 1 gets an array with only the A1 item. Order 2 gets NULL, because FILTER leaves the aggregate with no input rows and jsonb_agg returns NULL for no input. Wrap it in coalesce(..., '[]') if you want an empty array instead.
Choosing a function
- If the data is an array and you need each element, use
jsonb_array_elements(or_textfor scalars). - If the array elements are objects with a known shape, use
jsonb_to_recordsetwith typed columns. - If the keys of an object are data, use
jsonb_eachorjsonb_each_text. - If you only need to know whether something exists, skip expansion and use
@>or?. - If the document structure is irregular, use
jsonb_path_query, which tolerates missing parts in lax mode.
Exercise
Write a query that returns, for each order, the customer name and the number of line items in its items array. Orders whose items array is empty or missing must still appear, with a count of 0.
Show answer
Use a left lateral join and count the element column, so empty arrays give a count of 0: SELECT o.customer, count(i) AS itemcount FROM orders o LEFT JOIN LATERAL jsonbarray_elements(o.details -> 'items') AS i ON true GROUP BY o.id, o.customer; For a missing or empty array the left join yields one row with i = NULL, and count(i) ignores NULLs, so the result is 0. With the sample data, Ada gets 2 and Grace gets 1. If an items value could be a non-array, guard the argument with the CASE expression shown earlier.
Exercise
Using jsonbtorecordset, list every order id with each item's sku and qty, and explain what happens to an item object that has no qty key.
Show answer
SELECT o.id, x.sku, x.qty FROM orders o CROSS JOIN LATERAL jsonbtorecordset(o.details -> 'items') AS x(sku text, qty int); An item without a qty key still produces a row, and its qty column is NULL. Keys that are not declared in the column list, such as a color key, are ignored. If a qty value cannot be converted to int, such as the string "many", the query fails with an error.