SQL: HAVING
HAVING filters after grouping, WHERE before.
Rules
- WHERE filters rows
- HAVING filters groups
- Aggregates only in HAVING
Your turn
Three problems on this topic. You can run the query first.
- 1 · HAVING
- 2
- 3
Which course ids have at least 3 grade entries? Give the course id and the count.
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 3 | 4 |
| 5 | 3 | 2 |
| 4 | 3 | 1.3 |
| 7 | 1 | 4 |
| 7 | 2 | 3.3 |
| 1 | 2 | 4 |
| 2 | 1 | 2.7 |
| 1 | 3 | 1.7 |
| 4 | 4 | 2.7 |
| 6 | 4 | 3.7 |
| 2 | 4 | 2.7 |
| 2 | 2 | 3.3 |
| 6 | 1 | 1 |
+ − More tables: students, courses
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Max | Chemistry | 1 | Berlin |
| 2 | Anna | Law | 7 | Zürich |
| 3 | Hannah | Business | 3 | Berlin |
| 4 | Felix | Computing | 1 | Bern |
| 5 | Ben | Law | 7 | Bern |
| 6 | Greta | Computing | 6 | Bern |
| 7 | Nora | Business | 7 | Basel |
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 6 | Weber |
| 2 | Databases | 5 | Huber |
| 3 | Marketing | 4 | Weber |
| 4 | Statistics | 5 | Keller |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
Which cities have at least 2 students? Give the city and the count.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Felix | Law | 3 | Bern |
| 2 | Nora | Law | 7 | Bern |
| 3 | Greta | Chemistry | 2 | Bern |
| 4 | Eva | Business | 2 | Berlin |
| 5 | Max | Business | 4 | Wien |
| 6 | Clara | Business | 1 | Wien |
| 7 | Lena | Computing | 2 | Zürich |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Law | 4 | Keller |
| 2 | Marketing | 4 | Keller |
| 3 | Databases | 4 | Huber |
| 4 | Calculus | 5 | Meier |
grades
| student_id | course_id | grade |
|---|---|---|
| 3 | 2 | 3 |
| 4 | 1 | 2 |
| 2 | 1 | 3.3 |
| 5 | 3 | 3 |
| 2 | 4 | 4 |
| 6 | 1 | 4 |
| 1 | 3 | 3 |
| 2 | 3 | 1 |
| 7 | 2 | 1.7 |
| 1 | 2 | 3.3 |
| 2 | 2 | 3 |
| 1 | 4 | 3.7 |
Worked solution
SELECT city, COUNT(*) FROM students GROUP BY city HAVING COUNT(*) >= 2
Result on the sample data:
city | count
Bern | 3
Wien | 2
Typical mistake: WHERE filters rows, HAVING filters groups.
Common questions
When WHERE, when HAVING?
Conditions on single rows in WHERE, conditions on aggregates in HAVING.
