TechnicalEasy SQL & Databases
What is the difference between WHERE and HAVING?
Asked for Backend Developer, Full-Stack Developer
Why they ask this: A common online-test question that checks you understand how GROUP BY queries run.
Answer
WHEREfilters rows before grouping. It cannot use aggregate functions.HAVINGfilters groups afterGROUP BY. It can use aggregates such asCOUNTandAVG.
sql
-- Companies in Kathmandu with more than 5 open jobs
SELECT company_id, COUNT(*) AS open_jobs
FROM jobs
WHERE status = 'open' AND city = 'Kathmandu' -- row filter
GROUP BY company_id
HAVING COUNT(*) > 5; -- group filterThe logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Filter in WHERE whenever you can, because it reduces the rows that need grouping.
Can you explain this in your own words?