Last updated: August 27, 2026.
Aggregate functions calculate one result from multiple rows. The most common are COUNT, SUM, AVG, MIN, and MAX.
Summarize an entire table
SELECT
COUNT(*) AS order_count,
SUM(total_amount) AS total_revenue,
AVG(total_amount) AS average_order,
MIN(total_amount) AS smallest_order,
MAX(total_amount) AS largest_order
FROM orders;COUNT(*) counts rows. Other aggregates normally ignore NULL values in their input expression.
Calculate one result per group
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC;Every selected column that is not aggregated should normally appear in GROUP BY. This form works consistently across major SQL databases.
Count distinct values
SELECT COUNT(DISTINCT customer_id) AS active_customers
FROM orders
WHERE order_date >= '2026-01-01';Handle an empty aggregate
SELECT COALESCE(SUM(total_amount), 0) AS total_revenue
FROM orders
WHERE order_date >= '2030-01-01';Except for COUNT, an aggregate over no matching rows commonly returns NULL. COALESCE can supply a suitable default. See the MySQL aggregate function reference.