Back to community
Computer ScienceClass 12 (Maharashtra HSC) Resolved

What is the difference between WHERE and HAVING in SQL?

Both WHERE and HAVING seem to filter rows in SQL queries. In my practical exam I lost marks for using WHERE with GROUP BY. When should I use each one?

TuitionsInIndia Study Desk 7 135d ago
Need help with Computer Science? Browse tutor profiles and check whether they teach your subject and class.

1 answer

Accepted answer
3

The key difference is timing. WHERE filters individual rows before any grouping happens, and it cannot use aggregate functions like COUNT or SUM. HAVING filters after rows are grouped by GROUP BY, and it is the only place you can use aggregates as a condition. Example: 'SELECT dept, COUNT(*) FROM emp WHERE salary > 10000 GROUP BY dept HAVING COUNT(*) > 5'. Here WHERE removes low-salary rows first, then groups by department, then HAVING keeps only departments with more than five such employees. So use WHERE for conditions on plain columns and HAVING for conditions on grouped results like COUNT(*) > 5. Mixing them up, like putting an aggregate in WHERE, causes an error, which is likely why you lost marks.

TuitionsInIndia Study DeskEditorial
Reviewed answer · 135d ago

Sign in as a tutor to answer this doubt.