json_agg()

Collects all the input values, including nulls, into a JSON array. Values are converted to JSON as per to_json or to_jsonb.

Signature

json_agg ( anyelement ORDER BY input_sort_columns ) → json

Examples

SELECT json_agg(product ORDER BY id) FROM orders;
                             json_agg                             
------------------------------------------------------------------
 ["keyboard", "monitor", "keyboard", "mouse", "monitor", "cable"]
(1 row)

Run against PostgreSQL 18.6 on 2026-09-13. This is the output we got, not the documentation’s.

Want to run this against your own PostgreSQL server from an iPhone, iPad or Mac? These are ours — every connection goes straight from the device to your database, with no account and no server of ours in between.

Signature and description adapted from the PostgreSQL manual, used under the PostgreSQL License. PostgreSQL is a registered trademark of the PostgreSQL Community Association of Canada. This page is not affiliated with the PostgreSQL Global Development Group.