Query data

Summarize with aggregate functions

Use COUNT, SUM, AVG, MIN, and MAX to calculate one result from several rows.

8 minute lesson

~~~

Aggregate functions turn several input rows into a summary.

Suppose the paid orders contain totals 49.00, 18.50, and NULL. This query returns one row:

SELECT
  COUNT(*) AS order_count,
  COUNT(total) AS priced_orders,
  SUM(total) AS revenue,
  AVG(total) AS average_total,
  MIN(total) AS smallest_total,
  MAX(total) AS largest_total
FROM orders
WHERE status = 'paid';

The result is:

order_count | priced_orders | revenue | average_total
3           | 2             | 67.50   | 33.75

COUNT(*) counts rows. COUNT(total) counts only rows whose total is not NULL. SUM, AVG, MIN, and MAX also ignore NULL inputs.

This difference is important. A NULL total does not become zero. It means the value is missing or unknown, so the average uses two known totals rather than three orders.

When no rows match, COUNT(*) returns zero. Other aggregates commonly return NULL. If an interface needs a numeric zero, express that choice:

SELECT COALESCE(SUM(total), 0) AS revenue
FROM orders
WHERE status = 'refunded';

Filtering happens before aggregation. If the requirement says paid revenue, the WHERE clause must exclude pending and refunded rows.

Your action is to predict every aggregate result for three values: 10, 20, and NULL. Then run one query and compare your prediction.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →