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

  • WHERE filters rows before grouping. It cannot use aggregate functions.
  • HAVING filters groups after GROUP BY. It can use aggregates such as COUNT and AVG.
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 filter

The 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?

Back to question bank