HAVING

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.

Tutorials dojo strip

SQL HAVING Syntax

SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
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:

SELECT gender, COUNT(patient_id)
FROM Patients
GROUP BY gender
HAVING COUNT(patient_id) > 2;

SQL HAVING with ORDER BY

The next example also sorts the results in descending order of patient count:

SELECT gender, COUNT(patient_id)
FROM Patients
GROUP BY gender
HAVING COUNT(patient_id) > 2
ORDER BY COUNT(patient_id) DESC;

SQL HAVING Labs

Tutorials dojo strip
Scroll to Top