Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 24/ 160
02. Aggregations, Functions & Data Manipulation

Filtering Groups with HAVING (WHERE vs HAVING)

Filter rows before grouping with WHERE and groups after aggregation with HAVING.

BeginnerHAVING · WHERE vs HAVING3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

WHERE throws away rows you don't want; HAVING throws away groups you don't want.

Think of it like…

WHERE is the bouncer checking each person at the door; HAVING is the manager who looks at every table after people sit down and clears tables with fewer than four guests.

Where you’ve seen it

"Customers who spent over ₹10,000 on paid orders this year": WHERE status = 'paid' AND created_at >= '2026-01-01' filters orders, then GROUP BY customer_id HAVING SUM(amount) > 10000 filters customers.

Words you’ll hear

WHERE
Row-level filter applied before grouping.
HAVING
Group-level filter applied after GROUP BY.
Aggregate
A function over many rows: COUNT, SUM, AVG, MIN, MAX.
HAVING without GROUP BY
Treats the whole result as a single group.

Visual diagram

Loading interactive diagram

Theory & example queries

The rule of thumb

If the condition is about a single row (a status, a date, a category), it belongs in WHERE. If it's about a group (a count, a total, an average), it belongs in HAVING.

Putting a row condition in HAVING (HAVING status = 'paid') is an error if status isn't grouped. If it is grouped, the query works but filters after grouping, so the database aggregated rows it then throws away.

Both in one queryQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  SUM(amount)4FROM5  orders6WHERE7  status = 'paid'8GROUP BY9  customer_id10HAVING11  SUM(amount) > 10000;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative qualifying customers3 sample rows
Representative qualifying customers
customer_idsum
1712850
4217340
9110125

Note: Assumes these customers have paid-order totals above 10,000; values and currency units are illustrative.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Row condition → WHERE. Aggregate condition → HAVING.

Edge cases interviewers like

HAVING can use aggregates that aren't in the SELECT list: HAVING COUNT(DISTINCT product_id) >= 3 is valid even if you only select customer_id.

HAVING without GROUP BY treats the whole table as one group, so it returns one row or none. Standard SQL doesn't allow SELECT aliases in HAVING: PostgreSQL and SQL Server reject them, MySQL accepts them. Repeating the aggregate is the portable choice.

Users who bought three different productsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  user_id3FROM4  purchases5GROUP BY6  user_id7HAVING8  COUNT(DISTINCT product_id) >= 3;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative qualifying users3 sample rows
Representative qualifying users
user_id
7
23
91

Note: Each listed sample user is assumed to have bought at least three distinct products.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Repeat the aggregate in HAVING instead of relying on an alias.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Source

FROM collects rows

All rows from the table, plus any joins, form the starting set.

SQL at this step
1FROM2  orders
What to watch at this step
Rows
1,000,000
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

WHERE filters individual rows before they are grouped. HAVING filters groups after GROUP BY, so it can use aggregates like COUNT(*), SUM() or AVG(). Many real queries use both.

Why it matters: Mixing them up either throws an error (aggregates in WHERE) or quietly slows a query down (row filters in HAVING run after the expensive grouping). It's one of the most common SQL screening questions.

When to reach for it

  • Finding groups above or below a threshold (customers with more than 5 orders)
  • Detecting duplicates: GROUP BY email HAVING COUNT(*) > 1
  • Filtering rows first with WHERE, then groups with HAVING

When to avoid or be careful

  • Row-level conditions in HAVING
  • SELECT aliases in HAVING if the query must run on PostgreSQL or SQL Server
  • HAVING on a column that is neither grouped nor aggregated

WHERE vs HAVING vs a subquery

WHERE
Best for: Row conditions: status, dates, categories

Strengths: Runs before grouping, can use indexes, reduces work.

Watch out: Can't reference aggregates.

HAVING
Best for: Aggregate conditions: counts, sums, averages

Strengths: Filters on each group's computed result.

Watch out: Runs after grouping, so it's wasteful for row conditions.

Subquery + WHERE
Best for: Reusing an aggregate as a named column in later logic

Strengths: Lets you name the aggregate and filter or join on it.

Watch out: More verbose than HAVING for simple thresholds.

Interview signals & numbers to know

When this topic comes up

  • “Find customers with more than N orders”
  • “Find duplicate emails”
  • WHERE vs HAVING
  • “aggregate functions are not allowed in WHERE”
  • GROUP BY with a threshold

Benchmarks & rules of thumb

WHERE -
before GROUP BY
HAVING -
after GROUP BY
COUNT(*) > 1 -
the classic duplicate check

Common mistakes & follow-ups

Common interview mistakes

  • Writing WHERE COUNT(*) > 1 to find duplicates.
  • Moving a row filter into HAVING and making the query slower.
  • Referencing a SELECT alias in HAVING and getting "column does not exist" in PostgreSQL.

Likely interviewer follow-ups

  • Can you use HAVING without GROUP BY? What does it return?
  • How would you find emails that appear more than once in a users table?
  • Is there a performance difference between filtering a grouped column in WHERE versus HAVING?
Interview tip: Give the one-line rule (rows → WHERE, groups → HAVING), then write a query that uses both. It shows you know they work together, not as alternatives.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Filtering Groups with HAVING (WHERE vs HAVING) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Grouping Data with GROUP BY (Single & Multiple Columns)
Next topic
Conditional Logic with CASE WHEN ... THEN ... ELSE ... END