Once you can read and join data, the next step is to summarise it: how many employees per department, which departments cost the most, who earns more than the average. This guide covers aggregate functions, GROUP BY, HAVING and subqueries, with every result shown.
Part of the SQL Server for Beginners series. This article is the written version of lesson 3 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.
Watch lesson 3 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. Aggregate functions
- 2. GROUP BY
- 3. HAVING
- 4. Subqueries
- 5. Join or subquery?
- 6. Common mistakes
- 7. Practice
1. Aggregate functions
An aggregate function takes many rows and returns one value. This lesson uses the Employees and Departments tables from Lesson 2: JOINs.
SELECT COUNT(*) AS Employees, SUM(Salary) AS TotalSalary, AVG(Salary) AS AvgSalary,
MIN(Salary) AS Lowest, MAX(Salary) AS Highest
FROM Employees;
| Employees | TotalSalary | AvgSalary | Lowest | Highest |
|---|---|---|---|---|
| 6 | 24800 | 4133 | 3100 | 5200 |
The real average is 4133.33. AVG of an integer column returns an integer, so use AVG(CAST(Salary AS DECIMAL(10,2))) if you need decimals.
COUNT(*) versus COUNT(column)
COUNT(*) counts rows. COUNT(DeptId) counts only rows where DeptId is not NULL. Omar has no department, so COUNT(*) is 6 and COUNT(DeptId) is 5. All aggregates except COUNT(*) ignore NULL, which is often the reason a total looks too small.
2. GROUP BY
GROUP BY splits the rows into groups and calculates the aggregate for each group. Employees per department:
SELECT DeptId, COUNT(*) AS Employees
FROM Employees
GROUP BY DeptId;
| DeptId | Employees |
|---|---|
| NULL | 1 |
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
Employees without a department form their own group (NULL). Join to get readable names, then group by the name and sort the groups:
SELECT d.DeptName, SUM(e.Salary) AS Total, MAX(e.Salary) AS Highest
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId
GROUP BY d.DeptName
ORDER BY Total DESC;
| DeptName | Total | Highest |
|---|---|---|
| IT | 10000 | 5200 |
| Sales | 7800 | 4200 |
| HR | 3100 | 3100 |
The golden rule: every column in
SELECTmust either be inGROUP BYor inside an aggregate function. Selectinge.FirstNamewhile grouping only by department raises an error, because a group has many first names.
3. HAVING: filter groups
WHERE runs before groups exist, so it cannot filter on an aggregate. HAVING filters the groups afterwards. Departments with more than one employee:
SELECT d.DeptName, COUNT(*) AS Employees
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId
GROUP BY d.DeptName
HAVING COUNT(*) > 1;
| DeptName | Employees |
|---|---|
| IT | 2 |
| Sales | 2 |
You can use both. WHERE first removes rows (here Karim, who earns 3500 or less), then the rest is grouped, then HAVING keeps groups with an average above 4000:
SELECT d.DeptName, AVG(e.Salary) AS AvgSalary
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId
WHERE e.Salary > 3500
GROUP BY d.DeptName
HAVING AVG(e.Salary) > 4000;
| DeptName | AvgSalary |
|---|---|
| IT | 5000 |
The logical order of a query
SQL Server reads a query as: FROM and joins, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY. That explains why a column alias defined in SELECT cannot be used in WHERE, and why aggregates belong in HAVING.
4. Subqueries
A subquery is a query inside another query, in parentheses. Employees who earn more than the average (4133.33):
SELECT FirstName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
| FirstName | Salary |
|---|---|
| Amina | 4200 |
| Youssef | 5200 |
| Nadia | 4800 |
A subquery can return a list, used with IN. Employees who work on at least one project (the inner query returns 2, 5, 1, 2):
SELECT FirstName
FROM Employees
WHERE Id IN (SELECT EmpId FROM Projects);
| FirstName |
|---|
| Amina |
| Youssef |
| Nadia |
To find rows with no match, prefer NOT EXISTS:
SELECT e.FirstName
FROM Employees e
WHERE NOT EXISTS (SELECT 1 FROM Projects p WHERE p.EmpId = e.Id);
| FirstName |
|---|
| Salma |
| Karim |
| Omar |
NOT IN looks similar but has a trap: if the list contains even one NULL, it returns no rows at all. NOT EXISTS does not have this problem.
Subquery in FROM
SELECT d.DeptName, x.AvgSalary
FROM (SELECT DeptId, AVG(Salary) AS AvgSalary
FROM Employees GROUP BY DeptId) x
INNER JOIN Departments d ON d.DeptId = x.DeptId;
| DeptName | AvgSalary |
|---|---|
| Sales | 3900 |
| IT | 5000 |
| HR | 3100 |
A subquery in FROM must have an alias (x here).
Correlated subquery
The inner query uses a column of the outer query, so it runs once per outer row. Employees paid more than their own department’s average:
SELECT e.FirstName, e.Salary
FROM Employees e
WHERE e.Salary > (SELECT AVG(Salary) FROM Employees WHERE DeptId = e.DeptId);
| FirstName | Salary |
|---|---|
| Amina | 4200 |
| Youssef | 5200 |
Karim earns exactly his department average (he is alone in HR), so he is not above it, and Omar has no department, so the comparison with NULL is never true. Correlated subqueries are powerful but can be slow on large tables; lesson 7 shows cleaner alternatives with CTEs and window functions.
5. Join or subquery?
- Use a JOIN when you need columns from both tables.
- Use IN or EXISTS to filter by a list or by the existence of related rows.
- Use a subquery in FROM to summarise first and join afterwards.
- Choose the version that is easiest to read, and check performance on real data (see How to Find and Fix Slow Queries in SQL Server).
6. Common mistakes
- Putting an aggregate in
WHERE(“an aggregate may not appear in the WHERE clause”): useHAVING. - Selecting a column that is not in
GROUP BY. - Using
NOT INwith a list that can contain NULL. - Using
=with a subquery that returns several rows: useIN.
7. Practice
- Show each department’s total salary, only for totals above 5000.
- List the employees who earn less than the company average.
- Find the employees who work on more than one project.
Answers: (1) join, GROUP BY d.DeptName HAVING SUM(e.Salary) > 5000 returns IT (10000) and Sales (7800). (2) WHERE Salary < (SELECT AVG(Salary) FROM Employees) returns Salma, Karim and Omar. (3) join Projects to Employees, GROUP BY e.FirstName HAVING COUNT(*) > 1 returns Youssef.
Frequently asked questions
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after the aggregates are calculated.
Why does COUNT(column) give a smaller number than COUNT(*)?
COUNT(column) skips NULL values, COUNT(*) counts every row.
Is a subquery slower than a join?
Not necessarily. SQL Server often produces the same plan. Correlated subqueries on big tables are the case to watch.
What to learn next
Next, learn how to change data safely in Lesson 4: INSERT, UPDATE, DELETE and Transactions. Previous lesson: Lesson 2: JOINs.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries (this article)
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
- Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
