SQL

ARRAY_AGG and JSON_AGG (PostgreSQL)

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Roll up grouped rows into a PostgreSQL array or JSON array — often a faster replacement for the application doing the same "group children under parent" join.
SQL
Raw
-- All tag names per user, as a real PG array
SELECT user_id,
       ARRAY_AGG(tag_name ORDER BY tag_name) AS tags
FROM   user_tags
GROUP  BY user_id;

-- As a JSON array of objects — perfect for one-shot API responses
SELECT u.id, u.name,
       JSON_AGG(JSON_BUILD_OBJECT(
         'id', o.id, 'amount', o.amount, 'date', o.created_at
       ) ORDER BY o.created_at DESC) AS recent_orders
FROM   users u
LEFT   JOIN orders o ON o.user_id = u.id
GROUP  BY u.id, u.name;

-- Build a JSON object keyed by user id
SELECT JSON_OBJECT_AGG(id, name) AS users_by_id
FROM   users;

-- Filter NULLs out of the array (LEFT JOIN with no matches → NULL element)
SELECT u.id,
       ARRAY_AGG(o.id) FILTER (WHERE o.id IS NOT NULL) AS order_ids
FROM   users u
LEFT   JOIN orders o ON o.user_id = u.id
GROUP  BY u.id;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.