SQL · Module 6 · Lesson 11 min read

Aggregate Functions

The 5 classic aggregates

FunctionReturns
count(*)number of rows
count(col)number of non-NULL values
count(DISTINCT col)number of unique non-NULL values
sum(col)total
avg(col)average (mean)
min(col) / max(col)smallest / largest (works for numbers, text and dates)

Key rules

  • Aggregates collapse many rows into one row (unless you use GROUP BY)
  • All aggregates ignore NULLs except count(*)
  • On zero rows: count → 0, but sum/avg/max → NULL → wrap in COALESCE(sum(x), 0)
  • You can't mix aggregates and normal columns without GROUP BY: SELECT user_id, sum(amount) FROM expenses; ❌ → needs GROUP BY user_id
  • Aggregates can't go in WHERE (use HAVING)

More aggregates in PostgreSQL

  • Statistics: stddev(), variance()
  • Median & percentiles: percentile_cont(0.5) WITHIN GROUP (ORDER BY amount)
  • Most common value: mode() WITHIN GROUP (ORDER BY category_id)
  • Booleans: bool_and() (all true?), bool_or() (any true?)
  • Collecting: string_agg, array_agg, json_agg (lesson 6.4)

avg vs median

The average is pulled up by a few big values (one Rs. 8,500 paragliding trip). The median shows the "typical" expense better.

Rounding the results

round(avg(amount), 2) – averages often have many decimal places

Example

SQL
SELECT count(*)                AS expenses,       -- 31
       sum(amount)             AS total,          -- 76610.00
       round(avg(amount), 2)   AS average,        -- 2471.29
       min(amount)             AS smallest,       -- 450.00
       max(amount)             AS largest,        -- 8500.00
       min(spent_on)           AS first_day,      -- 2026-09-02
       max(spent_on)           AS last_day        -- 2026-11-10
FROM expenses;

-- count(*) vs count(column) vs count(DISTINCT)
SELECT count(*)              AS rows,             -- 6
       count(city)           AS with_city,        -- 5
       count(DISTINCT city)  AS unique_cities     -- 3
FROM users;

-- Median vs average
SELECT round(avg(amount), 2)                                     AS average,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY amount)       AS median,
       percentile_cont(0.9) WITHIN GROUP (ORDER BY amount)       AS p90
FROM expenses;

-- Aggregates on zero rows
SELECT count(*) AS cnt, sum(amount) AS total, COALESCE(sum(amount), 0) AS safe_total
FROM expenses WHERE user_id = 5;        -- 0 | NULL | 0

-- Boolean aggregates
SELECT bool_and(paid) AS all_paid, bool_or(paid) AS any_paid FROM bills;   -- false | true

-- ❌ Mixing without GROUP BY:
-- SELECT user_id, sum(amount) FROM expenses;
-- ERROR: column "expenses.user_id" must appear in the GROUP BY clause or be used in an aggregate function