Foundations › SQL › Aggregation & Analysis
Aggregation & AnalysisAggregate Functions: COUNT, SUM, AVG, MIN, MAX
Aggregate functions turn a set of rows into one value. They are the basis of any report: total sales, number of customers, average price.
COUNT(*) counts rows. Open in SQL Lab
COUNT(column) counts non-NULL values only, so the difference is the number of blanks. Open in SQL Lab
Smallest, largest and average. Open in SQL Lab
Total revenue: quantity × price per row, then sum. Open in SQL Lab
COUNT(DISTINCT ...) counts different values. Open in SQL Lab
For advanced readers Precision and performance
AVG(col) differs from SUM(col)/COUNT(*) when the column has NULLs because the divisor changes. For money use DECIMAL/NUMERIC instead of floating point to avoid rounding errors. COUNT(DISTINCT) is heavier than COUNT on huge tables.
Exercise 1 — Show the number of completed orders (status = 'completed').
WHERE then COUNT(*).
Exercise 2 — Show total revenue from order_items (quantity × unit_price) as revenue.
SUM(quantity * unit_price).
Exercise 3 — How many distinct customers have at least one order (orders table)?
COUNT(DISTINCT customer_id).
- COUNT, SUM, AVG, MIN and MAX summarize rows.
- COUNT(*) counts rows; COUNT(column) ignores NULL.
- COUNT(DISTINCT) counts different values.
Want an expert to do it for you?
Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.