Aggregate Functions
COUNT, SUM, AVG, MIN, MAX — compute summary values across rows
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Aggregate functions compute a single value from many rows.
| Function | What it does | |----------|-------------| | COUNT(*) | Count rows | | COUNT(col) | Count non-NULL values | | SUM(col) | Total of values | | AVG(col) | Average of values | | MIN(col) | Smallest value | | MAX(col) | Largest value |
SELECT
COUNT(*) AS total_orders,
COUNT(shipped_at) AS shipped_orders, -- NULL shipped_at excluded
SUM(amount) AS total_revenue,
AVG(amount) AS avg_order,
MIN(amount) AS smallest_order,
MAX(amount) AS largest_order
FROM orders;NULL handling: COUNT(*) counts all rows. COUNT(col) skips NULLs. AVG also ignores NULLs (only averages non-NULL values).
DISTINCT with aggregates:
sql COUNT(DISTINCT customer_id) -- count unique customers, not total orders
Examples
Sales summary
ROUND() cleans up floating-point decimals in AVG results
SELECT
COUNT(*) AS num_sales,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS total_revenue,
ROUND(AVG(amount), 2) AS avg_sale,
MAX(amount) AS biggest_sale
FROM sales
WHERE sale_date >= '2024-01-01';How well did you understand this?
Next in SQL & Databases
GROUP BY & HAVING