CleverSphere

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. 1 · HAVING
  2. 2
  3. 3

Which course ids have at least 3 grade entries? Give the course id and the count.

grades

student_idcourse_idgrade
734
532
431.3
714
723.3
124
212.7
131.7
442.7
643.7
242.7
223.3
611
+ More tables: students, courses

students

idnamemajorsemestercity
1MaxChemistry1Berlin
2AnnaLaw7Zürich
3HannahBusiness3Berlin
4FelixComputing1Bern
5BenLaw7Bern
6GretaComputing6Bern
7NoraBusiness7Basel

courses

idtitlecreditslecturer
1Calculus6Weber
2Databases5Huber
3Marketing4Weber
4Statistics5Keller

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

idnamemajorsemestercity
1FelixLaw3Bern
2NoraLaw7Bern
3GretaChemistry2Bern
4EvaBusiness2Berlin
5MaxBusiness4Wien
6ClaraBusiness1Wien
7LenaComputing2Zürich
+ More tables: courses, grades

courses

idtitlecreditslecturer
1Law4Keller
2Marketing4Keller
3Databases4Huber
4Calculus5Meier

grades

student_idcourse_idgrade
323
412
213.3
533
244
614
133
231
721.7
123.3
223
143.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.

Related

More topics