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?

Asked by Imran Shaikh 6 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

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.

K
Kavita Rao
380 pts· 45d ago

Sign in as a tutor to answer this doubt.