PostgreSQL JSONB Aggregation Array Builder
Aggregate rows into nested JSONB documents with jsonb_build_object and jsonb_agg, shaping API responses directly in SQL.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Which tables does this file reference?
- The references are `orders`, `order_items`, `order_tags`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.