DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT — Reading data
SQL Lesson 3: WHERE — Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL — The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 12

HAVING

Filtering groups — the WHERE clause for aggregates.

IN THIS CHAPTER

  • Why WHERE cannot be used with aggregate functions
  • HAVING to filter grouped results
  • The definitive WHERE vs HAVING comparison

12.1 - HAVING Basic

Departments with more than 2 employees

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

12.2 - WHERE vs HAVING - The Golden Rule

WHEREHAVING
FilterIndividual rowsGroups (after GROUP BY)
RunsBefore GROUP BYAfter GROUP BY
Aggregates?No - COUNT/AVG not allowed hereYes - purpose-built for them
ExampleWHERE salary > 60000HAVING AVG(salary) > 60000

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 👇

Exercise:

Tasks

1.👉Find departments that have more than 2 employees.
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.
Stuck? Read this task's