Aggregate Functions

Site Admin · 11 Sep 2026 · 2 views

Turning Many Rows Into One Summary

Aggregate functions collapse a column of values into a single number.

SELECT COUNT(*) FROM customers;
SELECT COUNT(city) FROM customers;      -- ignores NULLs
SELECT SUM(total), AVG(total) FROM orders;
SELECT MIN(price), MAX(price) FROM products;

The Core Five

  • COUNT(*): number of rows; COUNT(col) ignores NULLs.
  • SUM: total of numeric values.
  • AVG: arithmetic mean.
  • MIN / MAX: smallest and largest value.

Counting Distinct Values

SELECT COUNT(DISTINCT city) FROM customers;

Avoiding the Divide-by-NULL Trap

If no rows match, SUM, AVG, MIN and MAX return NULL, not zero. Wrap them when needed:

SELECT COALESCE(SUM(total), 0) FROM orders WHERE customer_id = 999;

Key Points

  • Aggregates summarise a whole column into one value.
  • COUNT(DISTINCT col) counts unique entries.
  • Aggregates return NULL on empty input; COALESCE fixes display.
  • They become truly powerful combined with GROUP BY.
Share this post:

Comments (0)

Please login or register to comment.