SQL JSON_AGG function
jsonb_agg(name) turns a column's values into one JSON array per group, and jsonb_agg(jsonb_build_object(...)) turns rows into an array of objects.
- Categoría
- Strings
- Returns
JSON array or jsonb- In this category
- 153 of 172
Sintaxis
JSON_AGG(expression)
jsonb_agg(expression [ORDER BY ...])
Each block is a separate form. The support table and the examples show which engine takes which.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | JSON_ARRAYAGG on SQL Server 2025; FOR JSON subqueries before |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Different name or syntax | JSON_ARRAYAGG (5.7.22+) |
| SQLite | Different name or syntax | json_group_array |
| Oracle | Different name or syntax | JSON_ARRAYAGG (12.2+) |
Ejemplos
PostgreSQL
SELECT region, jsonb_agg(name ORDER BY name) AS names FROM users GROUP BY region;
SQLite
SELECT region, json_group_array(name) AS names FROM users GROUP BY region;
MySQL
SELECT region, JSON_ARRAYAGG(name) AS names FROM users GROUP BY region;
Conviene saberlo
- jsonb_agg neither sorts nor removes duplicates. Element order is whatever order rows arrive in, unless you write ORDER BY inside the call: jsonb_agg(name ORDER BY name).
- An empty input set gives SQL NULL, not '[]': COALESCE(jsonb_agg(x), '[]'::jsonb) when the empty case must be an array.
- SQL Server gained JSON_ARRAYAGG in SQL Server 2025. Earlier versions build per-group arrays with a correlated subquery and FOR JSON PATH.
Questions about JSON_AGG
Array of scalars or of objects?
Both: jsonb_agg(name) for scalars, jsonb_agg(jsonb_build_object('name', name, 'id', id)) for objects. The build-function-inside-aggregate pattern covers most document needs.
Why is my array unordered?
Without ORDER BY inside the call, element order is input order, which no plan guarantees. An ORDER BY on the outer query sorts groups, not the elements inside each array.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.