SQL WHERE vs HAVING: Filter Rows before You Filter Groups
WHERE and HAVING both filter a SQL result, but they answer different questions. WHERE chooses input rows. HAVING filters groups after aggregation.…
A report total can become wrong even when the SQL runs without an error. One common cause is joining data at different levels of detail. This small example is useful practice for a data interview or a report review.
Imagine an orders table: order 10 has a total of €100 and order 11 has a total of €50. A separate items table has two rows for order 10 and one row for order 11. These are invented teaching values, not customer data.
Joining each order to its items produces three rows. The €100 order total appears twice because that order has two items. Adding the repeated order totals now gives €250 instead of the original €150. A join combines matching rows; it does not know which business amount you intend to add. The PostgreSQL join tutorial explains this matching behaviour.
If you need total order value, calculate it from orders at one row per order. If you need item-level information too, first decide what one result row should represent. You may need to summarise items by order before joining. Do not add DISTINCT as a quick fix without understanding which rows it removes.
In an interview, explain the repeated rows before suggesting a query change. That shows you understand the data, not just SQL syntax.
Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.
Explore opportunitiesWHERE and HAVING both filter a SQL result, but they answer different questions. WHERE chooses input rows. HAVING filters groups after aggregation.…
Two reports can disagree about “yesterday” even when they use the same events. One may use UTC dates while the other uses…
A finished report needs more than readable charts. Before sharing it with a team in Malta, check whether its rows and totals…