Aggregate Functions
Aggregate functions perform a calculation across multiple rows and return a single summary value - essential for turning raw rows of data into meaningful totals, averages, and counts.
Common Aggregate Functions
- COUNT() - counts the number of rows
- SUM() - adds up numeric values
- AVG() - calculates the average of numeric values
- MIN() - finds the smallest value
- MAX() - finds the largest value
Examples
-- Total number of customers
SELECT COUNT(*) FROM customers;
-- Total revenue across all orders
SELECT SUM(amount) FROM orders;
-- Average order amount
SELECT AVG(amount) FROM orders;
-- Highest and lowest order amounts
SELECT MAX(amount), MIN(amount) FROM orders;
Aggregates with WHERE
-- Total revenue from Noida customers only
SELECT SUM(o.amount)
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE c.city = 'Noida';
Aggregate functions ignore NULL values by default (except COUNT(*)), which can affect results like AVG() if a column has missing data - it's worth checking for NULLs first.