DataBolt

SQL LEARNING PLATFORM

10

CHAPTER 10

HAVING

Filtering groups — the WHERE clause for aggregates.

5

Learning Blocks

SQL

Interactive Queries

In This Chapter

Concepts you'll master

1

Why WHERE cannot be used with aggregate functions

2

HAVING to filter grouped results

3

The definitive WHERE vs HAVING comparison

12.1 - HAVING Basic

SQL QUERY
SELECT department, COUNT(*) AS headcount
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;

Common Mistake: Writing WHERE COUNT(*) > 2 throws an error. WHERE runs before aggregation — the COUNT values do not exist yet at that point in execution. Use HAVING.

Interview Tip 'What is the difference between WHERE and HAVING?' is asked in almost every data-related SQL interview. Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation.

Exercise

Practice your SQL skills

SQL EDITOR
Press semicolon (;) to auto-run query

Tasks

Complete all SQL challenges

1

Find departments that have more than 2 employees.

Current Task
2

Find departments where total salary is greater than 150000.

3

Find departments where average salary is greater than 60000.

4

Find departments where the highest salary is greater than 80000.

Need help solving this task?