aggregate

JSON_AGG

Builds a PostgreSQL JSON array from input values, including JSON null for SQL NULL. Repeated values remain; empty input returns SQL NULL. Example target: PostgreSQL 17; inline synthetic data; no extensions.

Formal Syntax & Structure

sql syntaxsql
JSON_AGG(expression ORDER BY sort_key)

Working Example

Example Snippetsql
WITH sample(id,x,y) AS (VALUES (1,1,2),(2,2,4),(3,3,6),(4,4,8),(5,NULL,4)) SELECT json_agg(x ORDER BY id) FROM sample;
SQL Reference