SQL: What is the difference between GROUP BY and HAVING?

asked 4 days ago9 viewsen

0

I would like to know the difference between the Group by and the Having clauses

Environment:PostgresWindows

🤖 AI diagnosis

by claude-sonnet-5 · 4 days ago

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

  1. #1 Conceptual confusion rather than a bug: GROUP BY aggregates rows into groups based on column values, while HAVING filters those already-grouped results based on aggregate conditions (unlike WHERE, which filters rows before grouping).

    80% confidence

    Try this

    Run: SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 5; and compare to the same query without HAVING to see the difference.
  2. #2 May be confusing HAVING with WHERE, since both filter data but at different stages of query execution.

    50% confidence

    Try this

    Try replacing HAVING COUNT(*) > 5 with WHERE COUNT(*) > 5 in the same query and observe the Postgres error message about aggregate functions not allowed in WHERE.
0 found this helpful · 0 disagreed
asked 4 days ago

1 Answer

0
🤖 AI-assisted

GROUP BY vs HAVING

These two clauses serve different purposes in a query:

  • GROUP BY collapses rows into groups based on the values of one or more columns, so you can apply aggregate functions (COUNT, SUM, AVG, etc.) per group instead of over the whole table.
  • HAVING filters the groups produced by GROUP BY, based on conditions involving aggregate functions. It runs after grouping/aggregation has happened.

This is different from WHERE, which filters individual rows before any grouping or aggregation occurs — and that's why you can't use aggregate functions in a WHERE clause.

Example:

SELECT dept, COUNT(*) 
FROM employees 
GROUP BY dept 
HAVING COUNT(*) > 5;

Here:

  1. GROUP BY dept groups all employees by department.
  2. COUNT(*) counts employees in each group.
  3. HAVING COUNT(*) > 5 keeps only the departments where that count exceeds 5.

If you try:

SELECT dept, COUNT(*) 
FROM employees 
WHERE COUNT(*) > 5 
GROUP BY dept;

Postgres (and most SQL engines) will raise an error, since COUNT(*) isn't available yet at the WHERE stage — the rows haven't been grouped/aggregated.

Summary:

  • WHERE → filters rows before grouping.
  • GROUP BY → groups rows for aggregation.
  • HAVING → filters groups after aggregation, typically using aggregate conditions.

Sign in to tell others whether this worked.

answered 4 days ago

Sign in and verify your email to post an answer.