Lesson 21 +10 XP

HAVING Clause

HAVING filters groups after grouping. This is different from WHERE, which filters rows before grouping.

The problem

You cannot use aggregate functions in WHERE:


sql
- **This FAILS**: SELECT Country, COUNT(*) FROM Customers

### WHERE COUNT(*) > 1

### GROUP BY Country;

The fix: HAVING


sql

### SELECT Country, COUNT(*)

### FROM Customers

### GROUP BY Country

### HAVING COUNT(*) > 1;

Keeps only countries with more than one customer.

WHERE vs HAVING

ClauseFilters
WHEREindividual rows, before grouping
HAVINGgroups, after grouping

Both together


sql

### SELECT CategoryID, AVG(Price)

### FROM Products

### WHERE Price > 10 - filter rows first

### GROUP BY CategoryID

### HAVING AVG(Price) > 20; - then filter groups

Order of clauses

SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY

TL;DR

  • HAVING filters groups.
  • WHERE filters rows.
  • WHERE comes before GROUP BY; HAVING comes after.
  • Use HAVING with aggregate functions.