Multiple Aggregates & Complex Grouping: Functions
Module: Aggregate Functions & Grouping
-- Multiple aggregates, single grouping
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_payroll,
AVG(salary) AS avg_salary,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees
GROUP BY department;
-- Multi-column grouping
SELECT
department,
job_title,
COUNT(*) AS count,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department, job_title;
-- Complete pattern
SELECT
region,
category,
COUNT(*) AS orders,
SUM(total) AS revenue,
AVG(total) AS avg_order
FROM orders
WHERE order_date >= '2024-01-01'
GROUP BY region, category
HAVING COUNT(*) >= 10
ORDER BY revenue DESC;
Multiple aggregates computed in one pass per group
All non-aggregate columns must be in GROUP BY
More grouping columns = more granular groups
WHERE filters rows, HAVING filters groups
ORDER BY can reference any aggregate
Core references in this topic include WHERE, =, <, >, <=, >=. Learn what each one does, when to use it, and the execution or engine rules that matter.
WHERE
Filters rows before projection and sorting. It decides which rows continue through the query pipeline.
SELECT ... FROM table WHERE condition;
Most performance issues start with a weak WHERE clause or a missing supporting index.