Part 14 / Topic 4 of 10
Building JSON from rows
The reverse direction: your API wants JSON, and the database can shape it directly. jsonb_build_object makes one object; jsonb_agg rolls rows up into an array; to_jsonb converts a whole row:
SELECT c.first_name,
jsonb_agg(
jsonb_build_object('order_id', o.order_id, 'status', o.status)
ORDER BY o.order_id
) AS orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
WHERE c.customer_id = 1
GROUP BY c.first_name;
first_name | orders
------------+------------------------------------------------------------------------------------------------------------------------
Asha | [{"status": "delivered", "order_id": 1}, {"status": "delivered", "order_id": 3}, {"status": "pending", "order_id": 7}]
(1 row)
One row out, API-shaped — the aggregate's inner ORDER BY (Part 4's trick) keeping the array deterministic. This pattern — join, group, jsonb_agg of jsonb_build_object — is how "give me the customer with their orders nested" leaves the database in one round trip instead of N+1 queries assembling it in code.
🧪 Quick quiz — answer from memory, then check.
- Which function turns a group of rows into one JSON array?
- How do you keep that array's element order stable?
Show the answers
jsonb_agg(of whatever each element should be — oftenjsonb_build_object).- An ORDER BY inside the aggregate call.
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.