Aggregate Functions
Calculate summary statistics on data
Aggregate functions perform calculations across multiple rows and return a single result.
Common Aggregate Functions
| Function | Description | Example |
|---|---|---|
| COUNT(*) | Count all rows | COUNT(*) |
| COUNT(col) | Count non-NULL values | COUNT(email) |
| SUM(col) | Total of values | SUM(total) |
| AVG(col) | Average value | AVG(price) |
| MIN(col) | Smallest value | MIN(created_at) |
| MAX(col) | Largest value | MAX(score) |
Basic Examples
-- Count total users
SELECT COUNT(*) AS total_users FROM users;
-- Sum all order totals
SELECT SUM(total) AS revenue FROM orders;
-- Average order value
SELECT AVG(total) AS avg_order FROM orders;
-- Find oldest and newest orders
SELECT
MIN(created_at) AS first_order,
MAX(created_at) AS last_order
FROM orders;COUNT Variations
-- Count all rows (including NULLs)
SELECT COUNT(*) FROM users;
-- Count non-NULL values in a column
SELECT COUNT(phone) FROM users; -- Users with phone numbers
-- Count unique values
SELECT COUNT(DISTINCT country) FROM users;
-- Difference shows users without phone
SELECT
COUNT(*) AS total,
COUNT(phone) AS with_phone,
COUNT(*) - COUNT(phone) AS without_phone
FROM users;Remember: All aggregate functions except COUNT(*) ignore NULL values.