Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
One of the most frequent questions in SQL interviews and architectural design reviews is: "What is the difference between WHERE and HAVING?". Both clauses filter data, but they operate at fundamentally different stages of the query execution pipeline. Understanding this distinction is mandatory for writing aggregate queries.
+-----------------------------------------------------------------+
| WHERE ==> Filters INDIVIDUAL ROWS BEFORE grouping occurs. |
| CANNOT use aggregate functions (e.g. WHERE AVG > 50).|
+-----------------------------------------------------------------+
|
v
+-----------------------------------------------------------------+
| GROUP BY ==> Collapses remaining rows into aggregate buckets. |
+-----------------------------------------------------------------+
|
v
+-----------------------------------------------------------------+
| HAVING ==> Filters SUMMARY GROUPS AFTER aggregation has computed.|
| CAN and DOES use aggregate functions! |
+-----------------------------------------------------------------+| Feature | WHERE Clause | HAVING Clause |
|---|---|---|
| Stage of Execution | Pre-aggregation (Filters raw table rows). | Post-aggregation (Filters aggregated summary rows). |
| Can use Aggregates? | NO (WHERE SUM(amount) > 100 is a syntax error!). | YES (HAVING SUM(amount) > 100 is valid!). |
| Operates on | Individual table rows. | Grouped buckets generated by GROUP BY. |
| Indexes Utilized? | Yes (Can use standard B-Tree indexes directly). | Generally no (Filters intermediate grouped memory buffers). |
Suppose management requests: "Find all departments with more than 5 active employees where the average salary exceeds ₹60,000."
WHERE Use Aggregate Functions?Consider this common error:
Because WHERE evaluates while scanning individual rows. At the moment row 1 is being read, the average salary of the entire department does not exist yet! Aggregates only exist after all rows have been scanned and grouped.
HAVING is_active = TRUE, this is an architectural anti-pattern! It forces the engine to group millions of inactive rows before filtering them out in memory. Always filter raw rows in WHERE as early as possible!FROM & JOINWHEREGROUP BYHAVINGSELECTDISTINCTORDER BYLIMITWHERE and HAVING clauses?SELECT dept, SUM(sales) FROM stores WHERE SUM(sales) > 100000 GROUP BY dept; fail?HAVING clause execute?HAVING status = 'Active' instead of WHERE status = 'Active'?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Grouping Data with GROUP BY | Using DISTINCT with Aggregate Functions |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.