SQL HAVING Keyword
The HAVING clause is used to filter groups of records after they have been grouped using GROUP BY. It is typically used with aggregate functions like COUNT, SUM, AVG, MAX, or MIN. Unlike WHERE, which filters rows before grouping, HAVING filters after grouping.
SQL HAVING Syntax
SQL
x
1
SELECT column_name, AGGREGATE_FUNCTION(column_name)
2
FROM table_name
3
GROUP BY column_name
4
HAVING AGGREGATE_FUNCTION(column_name) condition;
SQL HAVING with GROUP BY Example
The following SQL lists how many patients exist for each gender in the Patients table, and only includes genders that have more than 2 patients:
SQL
1
1
SELECT gender, COUNT(patient_id)
2
FROM Patients
3
GROUP BY gender
4
HAVING COUNT(patient_id) > 2;

SQL HAVING with ORDER BY
The next example also sorts the results in descending order of patient count:
SQL
1
1
SELECT gender, COUNT(patient_id)
2
FROM Patients
3
GROUP BY gender
4
HAVING COUNT(patient_id) > 2
5
ORDER BY COUNT(patient_id) DESC;
