// aggregates reference

SQL JSON_ARRAYAGG function

Aggregates the rows of a group into one JSON array value.

Category
Aggregates
Returns
json
In this category
17 of 52

Syntax

JSON_ARRAYAGG(col) | JSON_ARRAYAGG(col ORDER BY col)

Engine support

EngineSupportNotes
SQL Server Yes SQL Server 2025 / Azure SQL; earlier versions build arrays with FOR JSON PATH
PostgreSQL Yes PostgreSQL 16+; json_agg and jsonb_agg work on every version
MySQL Yes no ORDER BY inside the aggregate
SQLite Not built in use json_group_array
Oracle Yes Supported under this name.

Examples

MySQL

SELECT dept_id, JSON_ARRAYAGG(name) FROM employees GROUP BY dept_id;

Oracle

SELECT JSON_ARRAYAGG(name ORDER BY name NULL ON NULL) FROM employees;

PostgreSQL

SELECT dept_id, jsonb_agg(name ORDER BY name) FROM employees GROUP BY dept_id;

Good to know

  • Without ORDER BY the array order is undefined. SQL Server 2025, PostgreSQL and Oracle accept JSON_ARRAYAGG(x ORDER BY x); MySQL rejects it with a syntax error, so order a derived table first and accept that the order is not guaranteed.
  • NULL defaults split: the standard form drops NULLs (ABSENT ON NULL) in Oracle, SQL Server and PostgreSQL's JSON_ARRAYAGG, while MySQL's JSON_ARRAYAGG and PostgreSQL's json_agg keep them as JSON null. Write NULL ON NULL or ABSENT ON NULL where the engine accepts it.
  • To collect key/value rows into an object instead, you want JSON_OBJECTAGG.

Questions about JSON_ARRAYAGG

What is JSON_ARRAYAGG in PostgreSQL?

PostgreSQL 16 added JSON_ARRAYAGG itself. On any version, json_agg and jsonb_agg do the same job; they keep NULLs as JSON null, while JSON_ARRAYAGG drops them by default.

Does JSON_ARRAYAGG include NULL values?

Engine-dependent: MySQL includes them as JSON null; Oracle, SQL Server and PostgreSQL's JSON_ARRAYAGG omit them unless you write NULL ON NULL.

How do I order the array elements?

Put ORDER BY inside the aggregate on SQL Server 2025, PostgreSQL, Oracle and SQLite 3.44+ (json_group_array). MySQL has no supported way to order JSON_ARRAYAGG.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

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