Aggregate Functions and GROUP BY

Most examples use this employees table:

idnamedeptsalarycity
1AshaIT65000Pune
2RaviHR42000Mumbai
3MeeraIT78000Pune
4KaranSales51000Delhi
5NehaHR47000Pune
FunctionReturns
COUNT()Number of rows
SUM()Total
AVG()Average
MIN() / MAX()Smallest / largest value
SQL
SELECT dept, COUNT(*) AS staff, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept;
+-------+-------+------------+ | dept | staff | avg_salary | +-------+-------+------------+ | IT | 2 | 71500.00 | | HR | 2 | 44500.00 | | Sales | 1 | 51000.00 | +-------+-------+------------+

HAVING

WHERE filters rows before grouping; HAVING filters groups after grouping.

SQL
SELECT city, SUM(salary) AS total
FROM employees
GROUP BY city
HAVING SUM(salary) > 100000;
+------+--------+ | city | total | +------+--------+ | Pune | 190000 | +------+--------+

Logical Order of Execution

Text
FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT
Track your progress through the SQL course