Data Engineering

SQL WHERE vs HAVING: Filter Rows before You Filter Groups

Huwell Consultancy editorial2 min read

WHERE and HAVING both filter a SQL result, but they answer different questions. WHERE chooses input rows. HAVING filters groups after aggregation. A small orders example makes the difference easier to see.

Define the report first

Imagine a table with customer, status and amount. Ada has two completed orders worth €20 and €40, plus a cancelled order worth €100. Ben has one completed order worth €30. These are invented learning values. We want customers whose completed-order total is above €50.

SELECT customer, SUM(amount) AS total
FROM orders
WHERE status = 'completed'
GROUP BY customer
HAVING SUM(amount) > 50;

WHERE removes the cancelled order before adding values. Ada’s completed total is €60 and Ben’s is €30. HAVING keeps Ada’s group and removes Ben’s. The PostgreSQL aggregate tutorial explains this distinction between row and group filtering.

Change one thing and predict the answer

Add a completed €25 order for Ben. His total becomes €55, so both customers now pass. Next, change the threshold to above €60. Ada’s total equals €60 and does not pass a strict greater-than comparison. Write down the expected result before running each version.

A useful review question

Ask whether a condition describes an individual row or an aggregated result. Do not move a condition between WHERE and HAVING just because a query produces an error. Understand the intended report first. In a data interview, explain which records enter the calculation and why the final groups remain.

Sources and further reading

Explore current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision