Video in progress

How do you get an order and its line items as ready-made JSON in a single query?

In PostgreSQL, json_build_object builds one object, and json_agg collects the rows of a group into an array. Combine the two and you get "order + items array" as one row.

📖 Answer

SELECT json_build_object(
         'id',     o.id,
         'status', o.status,
         'items',  COALESCE(
                     json_agg(json_build_object(
                       'sku', i.sku,
                       'qty', i.quantity
                     ) ORDER BY i.id) FILTER (WHERE i.id IS NOT NULL),
                     '[]'::json)
       ) AS order_json
FROM orders o
LEFT JOIN order_items i ON i.order_id = o.id
WHERE o.id = 42
GROUP BY o.id;

There are two subtle points. For an order with no items, the LEFT JOIN gives one NULL row and json_agg returns [null], which is why you need FILTER and COALESCE. The ORDER BY inside json_agg sets the order in the array; without it, the order isn't guaranteed.

When this is useful: a report or "read-only" endpoint, where the data is assembled from several tables and Java just has to pass it along. No N+1 queries, and no loading a collection in the ORM.

But where there is a lot of business logic, I still read into an entity or DTO. Building big JSON inside SQL is awkward to test and to change.