The HAVING clause in SQL is used to filter records that are grouped by the GROUP BY clause. Unike the WHERE clause, which operates on individual rows, the HAVING clause works on groups (or aggregates) of rows.
SQL Having Syntax
SQL
x
1
SELECT column1, column2, aggregate_function(column3)
2
FROM table_name
3
GROUP BY column1, column2
4
HAVING condition;
SQL Having Basic Example
This query groups the result by doctor’s first and last name, counts how many appointments each doctor has, and filter out those with 2 or fewer appointments.
SQL
1
1
SELECT d.first_name, d.last_name, COUNT(a.appointment_id) AS total_appointments
2
FROM Doctors d
3
JOIN Appointments a ON d.doctor_id = a.doctor_id
4
GROUP BY d.first_name, d.last_name
5
HAVING COUNT(a.appointment_id) > 2;
