SQL

SQL Having

SQL Having

This page covers SQL Having clause.

The statement “having” adds a specified condition to a “select” statement.

It allows filtering data with grouped or aggregated query.

Let’s use the table “student_info” from the previous tutorials.

idfirstNamelastNameage
1JohnSmith21
2PatrickCasey26
3SamAdams19
4MikeGarciaNULL
5PatrickDumont21

Having

The clause “having” can help when retrieving data through the “select” statement.

It is often used with the “group by” clause.

Let’s look at a previous example from the group by tutorial.

The scenario retrieves all student ages, and summarises them into sorted groups.

SELECT COUNT(age) AS n, age FROM student_info
GROUP BY age
ORDER BY COUNT(age);
nage
0NULL
119
126
221

If we want to search and select only age groups that have a minimum of student records, we cannot implement “COUNT(age) > 1” to a “select” or “where” statement.

The below query produces an error.

SELECT COUNT(age) > 1 AS n, age FROM student_info
GROUP BY age
ORDER BY COUNT(age);

The below query produces an error.

SELECT COUNT(age)AS n, age FROM student_info
WHERE COUNT(age) > 1
GROUP BY age
ORDER BY COUNT(age);

The above queries can work with the “having” statement.

Let’s look at a successfully executing example.

SELECT COUNT(age)AS n, age FROM student_info
GROUP BY age
HAVING COUNT(age) > 1
ORDER BY COUNT(age);
nages
221

The query filters through the data and selects only age groups that have at least 2 student records. The table contains 2 students that have 21 years of age.


Next: SQL Set