SQL · Module 6 · Lesson 41 min read

FILTER, STRING_AGG, ARRAY_AGG & JSON_AGG

FILTER – conditional aggregates (PostgreSQL) ⭐

scss
count(*) FILTER (WHERE amount > 5000)
sum(amount) FILTER (WHERE category_id = 7)
  • Cleaner than sum(CASE WHEN … THEN amount END)
  • Several different totals in one query, one table scan
  • Perfect for pivot-style reports (one column per category or month)

STRING_AGG – join values into text

string_agg(title, ', ' ORDER BY spent_on) → 'Groceries, Taxi, Dinner'

  • Second argument: the separator
  • ORDER BY inside controls the order
  • string_agg(DISTINCT city, ', ') – unique values only

ARRAY_AGG – collect into an array

array_agg(title ORDER BY amount DESC) → {Paragliding,Jacket,Fuel}

  • Access items: (array_agg(title ORDER BY amount DESC))[1] → the top item
  • Unnest it back into rows with unnest() (Unit 13)

JSON_AGG / JSONB_AGG – build JSON for your API

  • json_agg(e) – each row becomes a JSON object in an array
  • json_build_object('title', title, 'amount', amount) – custom objects
  • Nested JSON: users with an array of their expenses — exactly what a frontend wants

jsonb_object_agg

jsonb_object_agg(category, total) → {"Food": 1200, "Bills": 900} (key-value object)

These "collecting" aggregates are great for APIs (one query returns nested data) and for readable reports. For very large groups, consider pagination instead.

Example

SQL
-- FILTER: several totals in one pass
SELECT u.name,
       count(*)                                         AS all_expenses,
       count(*) FILTER (WHERE e.amount >= 5000)         AS large_ones,
       sum(e.amount) FILTER (WHERE e.category_id IN (7, 8))  AS food_total,
       sum(e.amount) FILTER (WHERE 'social' = ANY(e.tags))   AS social_total
FROM expenses e
JOIN users u ON u.id = e.user_id
GROUP BY u.name
ORDER BY u.name;

-- STRING_AGG: everything each user bought in November, in order
SELECT u.name,
       string_agg(e.title, ', ' ORDER BY e.spent_on) AS november_items
FROM expenses e JOIN users u ON u.id = e.user_id
WHERE e.spent_on >= '2026-11-01'
GROUP BY u.name;
-- Asha Sharma | Movie tickets, Monthly groceries, Bus pass

-- Cities and their residents
SELECT city, string_agg(split_part(name, ' ', 1), ' & ' ORDER BY name) AS people
FROM users WHERE city IS NOT NULL GROUP BY city;
-- Kathmandu | Asha & Sita ...

-- ARRAY_AGG: top expense per user via the first array element
SELECT user_id, (array_agg(title ORDER BY amount DESC))[1] AS biggest
FROM expenses GROUP BY user_id ORDER BY user_id;

-- JSON for an API: each user with a nested list of their bills
SELECT json_build_object(
         'user', u.name,
         'bills', json_agg(json_build_object('title', b.title, 'amount', b.amount, 'due', b.due_date)
                           ORDER BY b.due_date)
       ) AS payload
FROM users u JOIN bills b ON b.user_id = u.id
GROUP BY u.id
ORDER BY u.id
LIMIT 1;
-- {"user" : "Asha Sharma", "bills" : [{"title" : "Internet", ...}, {"title" : "Rent", ...}]}

-- Key-value object: totals by category for one user
SELECT jsonb_object_agg(c.name, t.total) AS by_category
FROM (SELECT category_id, sum(amount) AS total FROM expenses WHERE user_id = 2 GROUP BY category_id) t
JOIN categories c ON c.id = t.category_id;