Aggregate rows into JSON
The aggregate produces the array; the build function names the fields.
The task
An API endpoint wants each customer with their orders as a JSON array, produced by the database in one query.
The snippet
Written for PostgreSQL. Versions for MySQL and SQLite are under Variations.
SELECT customer_id,
JSON_AGG(
JSON_BUILD_OBJECT('id', id,
'date', order_date,
'amount', amount)
ORDER BY order_date
) AS orders_json
FROM orders
GROUP BY customer_id
ORDER BY customer_id;
工作原理
JSON_BUILD_OBJECT turns each order row into an object with named keys; JSON_AGG collects those objects into an array per group, and the ORDER BY inside the aggregate fixes the element order. Every engine ships its own pair: MySQL has JSON_ARRAYAGG with JSON_OBJECT, SQLite json_group_array with json_object, Oracle and SQL Server 2025 have JSON_ARRAYAGG with JSON_OBJECT, and older SQL Server versions use FOR JSON PATH.
Variations
MySQL: JSON_ARRAYAGG + JSON_OBJECT
MySQLSELECT customer_id,
JSON_ARRAYAGG(JSON_OBJECT('id', id,
'date', order_date,
'amount', amount)) AS orders_json
FROM orders
GROUP BY customer_id;
SQLite: json_group_array + json_object
SQLiteSELECT customer_id,
json_group_array(json_object('id', id,
'date', order_date,
'amount', amount)) AS orders_json
FROM orders
GROUP BY customer_id;
Questions that come up
Is the JSON element order guaranteed?
On PostgreSQL, yes, because the ORDER BY is inside the aggregate. MySQL's JSON_ARRAYAGG accepts no ORDER BY and its element order is undefined, so sort in the application if order matters there. SQLite's json_group_array follows the order rows reach the aggregate; SQLite 3.44+ also accepts an ORDER BY inside the call.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.