SQL data filtering: Differences between WHERE and HAVING clauses
The HAVING and WHERE clauses in SQL are both used to filter data, but their functions are different. The WHERE clause works on individual rows, while the HAVING clause works on aggregated results.
Difference example
Suppose we have two tables: Lecturers
and Lecturers_Specialization
, and we want to find the lecturers with the most areas of expertise.
The initial query using the WHERE clause does not give the expected results:
<code class="language-sql">SELECT L.LectID, Fname, Lname FROM Lecturers L, Lecturers_Specialization S WHERE L.LectID = S.LectID AND COUNT(S.Expertise) >= ALL (SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID);</code>
This is because the WHERE clause filters a single row, and the COUNT(S.Expertise) >= ALL
comparison cannot be applied to a single row.
The correct query uses the HAVING clause:
<code class="language-sql">SELECT L.LectID, Fname, Lname FROM Lecturers L, Lecturers_Specialization S WHERE L.LectID = S.LectID GROUP BY L.LectID, Fname, Lname HAVING COUNT(S.Expertise) >= ALL (SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID); </code>
HAVING clause acts on the aggregated results to ensure that the comparison is applied to the number of areas of expertise for each instructor.
Rules of thumb and optimization
Generally speaking, the WHERE clause is used before the GROUP BY clause to filter individual rows; the HAVING clause is used after the GROUP BY clause to filter aggregate results.
Additionally, queries can be optimized using ANSI JOIN syntax instead of L, S θ join syntax:
<code class="language-sql">SELECT L.LectID, Fname, Lname FROM Lecturers L JOIN Lecturers_Specialization S ON L.LectID=S.LectID GROUP BY L.LectID, Fname, Lname HAVING COUNT(S.Expertise)>=ALL (SELECT COUNT(Expertise) FROM Lecturers_Specialization GROUP BY LectID)</code>
The above is the detailed content of SQL HAVING vs. WHERE: When to Use Each Clause for Data Filtering?. For more information, please follow other related articles on the PHP Chinese website!