iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL Aggregate Functions

Aggregate functions collapse many rows into one summary value. They're the backbone of reports, dashboards, and analytics.

The big five

FunctionWhat it returns
COUNT(*)Number of rows, including NULLs.
COUNT(col)Number of non-NULL values in col.
SUM(col)Total of numeric values.
AVG(col)Arithmetic mean.
MIN(col) / MAX(col)Smallest / largest value.

Per-group aggregation

Pair with GROUP BY to bucket rows before summarising:

SQL
SELECT country,
       COUNT(*)      AS customers,
       AVG(lifetime_value) AS avg_value
FROM customers
GROUP BY country
ORDER BY customers DESC;

Aggregates and NULL

  • All aggregates except COUNT(*) skip NULLs.
  • SUM of zero rows returns NULL, not 0. Wrap in COALESCE(SUM(x), 0) if you need a number.
Tip: Anywhere you'd reach for a loop in code to compute a total or average, you almost certainly want an aggregate query instead. Let the DB do the work.

Example

Example
SELECT COUNT(*) AS rows,
       AVG(price) AS avg_price,
       MAX(price) AS max_price
FROM products;
Try it Yourself »

Exercise

Aggregate that always counts NULL rows.

SELECT (*) FROM customers;

Test yourself

Q1. Which is NOT an aggregate function?
Q2. SUM of zero rows returns…
Q3. Aggregates always skip NULL except…

Discussion

Loading…