json

jsonb_agg

Postgres aggregate that collects rows into a jsonb array. Its sibling jsonb_object_agg builds a jsonb object from key/value pairs.

jsonb_agg(expression [ORDER BY ...])

Parameters / Modifiers

Parameter Purpose
ORDER BY Control element order inside the resulting array
jsonb_object_agg(k, v) Aggregate key/value pairs into a jsonb object
FILTER (WHERE ...) Conditional inclusion of rows
COALESCE(jsonb_agg(x), '[]') Guard against NULL for empty groups

Examples

SELECT jsonb_agg(name ORDER BY name) FROM users;

JSON array of usernames sorted alphabetically

SELECT jsonb_agg(to_jsonb(u.*)) FROM users u;

Array of full user objects as jsonb

SELECT jsonb_object_agg(code, name) FROM countries;

Build {"US": "United States", ...} lookup object

SELECT jsonb_agg(id) FILTER (WHERE active) FROM users;

Only active users included in the array

Dialect notes / Gotcha

Postgres-only. Returns NULL for empty input, not '[]'::jsonb — wrap in COALESCE(jsonb_agg(x), '[]').

Related functions

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