4 min read
•Question 29 of 29easyWhat are SQL aggregate functions?
Summarizing data with aggregates.
What You'll Learn
- Common aggregate functions
- Usage with GROUP BY
- Filtering aggregates
Basic Aggregate Functions
query.sqlSQL
SELECT
COUNT(*) AS total_rows,
COUNT(email) AS emails_not_null,
COUNT(DISTINCT country) AS unique_countries,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount,
MIN(amount) AS min_amount,
MAX(amount) AS max_amount
FROM orders;COUNT Variations
query.sqlSQL
-- Count all rows
SELECT COUNT(*) FROM users;
-- Count non-NULL values
SELECT COUNT(phone) FROM users;
-- Count distinct values
SELECT COUNT(DISTINCT country) FROM users;With GROUP BY
query.sqlSQL
SELECT
country,
COUNT(*) AS user_count,
AVG(age) AS avg_age
FROM users
GROUP BY country;
-- Multiple grouping columns
SELECT
country,
city,
COUNT(*) AS user_count
FROM users
GROUP BY country, city;Filtering with HAVING
query.sqlSQL
-- WHERE filters rows, HAVING filters groups
SELECT
category,
COUNT(*) AS product_count,
AVG(price) AS avg_price
FROM products
WHERE status = 'active'
GROUP BY category
HAVING COUNT(*) > 5 AND AVG(price) > 50
ORDER BY avg_price DESC;With CASE (Conditional Aggregation)
query.sqlSQL
SELECT
COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count,
COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive_count,
SUM(CASE WHEN gender = 'M' THEN salary ELSE 0 END) AS male_salary_total
FROM employees;String Aggregation
query.sqlSQL
-- MySQL
SELECT department, GROUP_CONCAT(name) AS employees
FROM employees GROUP BY department;
-- PostgreSQL
SELECT department, STRING_AGG(name, ', ') AS employees
FROM employees GROUP BY department;