// strings reference

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.

카테고리
Strings
Returns
JSON array or jsonb
In this category
153 of 172

구문

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.

엔진 지원

엔진Support메모
SQL Server Different name or syntax JSON_ARRAYAGG on SQL Server 2025; FOR JSON subqueries before
PostgreSQL 예 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+)

예시

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;

알아 두면 좋은 정보

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.