aggregate

ARRAY_AGG

Collects grouped values into a single array, preserving order when ORDER BY is supplied. This is a Postgres feature; MySQL has no direct array type but JSON_ARRAYAGG serves the same role.

ARRAY_AGG(expr [ORDER BY ...] [FILTER (WHERE ...)])

Parameters / Modifiers

Parameter Purpose
ORDER BY Control element order in the resulting array
DISTINCT Collapse duplicates before aggregating
FILTER (WHERE ...) Only include rows meeting a predicate
JSON_ARRAYAGG MySQL 8 equivalent producing a JSON array

Examples

SELECT ARRAY_AGG(id ORDER BY id) FROM users;

Postgres integer array of user IDs, ascending

SELECT dept, ARRAY_AGG(DISTINCT skill) FROM emp GROUP BY dept;

Unique skills per department as a text array

SELECT JSON_ARRAYAGG(name) FROM users;

MySQL 8 equivalent producing a JSON array

SELECT ARRAY_AGG(name) FILTER (WHERE active) FROM users;

Postgres: only active users included in the array

Dialect notes / Gotcha

Postgres-only for true arrays; MySQL/SQLite emulate via JSON_ARRAYAGG (MySQL 8) or json_group_array (SQLite). ARRAY_AGG with no rows returns NULL rather than an empty array — COALESCE with '{}'.

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet