All SQL topics
SQL TOPIC

SQL COUNT, SUM and AVG: totals and averages

Aggregate functions turn many rows into one number: how many, how much, on average.

COUNT(*) counts rows, SUM adds values, AVG averages them, and MIN and MAX find the extremes. ROUND(AVG(x), 2) keeps money readable.

Filter first with WHERE (for example only paid orders), then aggregate, or your total will include rows that should not count.

Worked example

How much revenue came from order lines, in total?

SELECT ROUND(SUM(quantity * unit_price), 2) AS revenue
FROM order_items;
Result on the sample data
revenue
38849.1

Common mistakes

  • Summing prices instead of quantity × price.
  • Averaging a column that already contains averages.