PostgreSQL JSONB Aggregation Array Builder

Aggregate rows into nested JSONB documents with jsonb_build_object and jsonb_agg, shaping API responses directly in SQL.

SqlData Integrity

Code

sqlsnippet
30 lines
-- PostgreSQL 订单与其条目一次查询聚合成嵌套 JSON
SELECT
  jsonb_build_object(
    'order_id', o.id,
    'status', o.status,
    'total_cents', o.total_cents,
    'placed_at', to_char(o.placed_at, 'YYYY-MM-DD"T"HH24:MI:SS'),
    'items', COALESCE(
      jsonb_agg(
        jsonb_build_object(
          'sku', i.sku,
          'quantity', i.quantity,
          'unit_cents', i.unit_cents
        ) ORDER BY i.line_no
      ) FILTER (WHERE i.id IS NOT NULL),
      '[]'::jsonb
    )
  ) AS order_document
FROM orders o
LEFT JOIN order_items i ON i.order_id = o.id
WHERE o.id IN ('ord-1', 'ord-2')
GROUP BY o.id, o.status, o.total_cents, o.placed_at
ORDER BY o.id;

-- 数组打包键值对:标签表转对象
SELECT
  t.order_id,
  jsonb_object_agg(t.tag_key, t.tag_value) AS tags_object
FROM order_tags t
GROUP BY t.order_id;

How the snippet works

What runs here is SELECT — orders, order_items and order_tags are the objects involved.

What the statements actually assemble: one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

The orders table is the working surface here.

Statements that matter

SELECT
t.order_id,
jsonb_object_agg(t.tag_key, t.tag_value) AS tags_object
FROM order_tags t
GROUP BY t.order_id;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `orders`, `order_items`, `order_tags`, with one join tying the pair together.