π AggregationbeginnerCommonly used
How to use SUM, AVG, MIN and MAX in SQL
Calculate totals, averages, and extremes across rows.
SUM β total of a columnAll databases
SELECT SUM(total) AS revenue
FROM orders
WHERE status = 'completed';Adds up all values in the column. NULL values are ignored.
AVG β average valueAll databases
SELECT
AVG(age) AS avg_age,
ROUND(AVG(age), 1) AS avg_age_rounded
FROM users;Calculates the arithmetic mean. Use ROUND() to control decimal places.
MIN and MAXAll databases
SELECT
MIN(total) AS smallest_order,
MAX(total) AS largest_order,
MAX(created_at) AS latest_order
FROM orders;MIN and MAX work on numbers, dates, and strings.
Multiple aggregates in one queryAll databases
SELECT
COUNT(*) AS total_orders,
SUM(total) AS revenue,
AVG(total) AS avg_order_value,
MIN(total) AS min_order,
MAX(total) AS max_order
FROM orders
WHERE status = 'completed';Combine multiple aggregate functions in one query.
Aggregates per groupAll databases
SELECT
country,
COUNT(*) AS users,
AVG(age) AS avg_age,
MAX(age) AS oldest
FROM users
GROUP BY country
ORDER BY users DESC;All aggregate functions work with GROUP BY.
Common Mistakes
- βAll aggregate functions ignore NULL values β this can give misleading results
- βAVG of integers gives a decimal β wrap in ROUND() if needed