Why "WHERE" exists in SQL? Because "HAVING" can do its tasks plus more than that

Viewed 42

Why "WHERE" exists in SQL? Because "HAVING" can do its tasks plus more than that

1 Answers

Try using HAVING to do this query:

Sum the total sales per country for product 'XYZ'

SELECT country, SUM(amount)
FROM sales
GROUP BY country
HAVING product = 'XYZ'

No, that won't do it, because the groups will include sales for all products. And the HAVING condition is invalid because there are multiple products in each grouping.

The purpose of HAVING is to filter groups, after an aggregation is applied.

The purpose of WHERE is to filter rows, before an aggregation is applied.

SELECT country, SUM(amount)
FROM sales
WHERE product = 'XYZ'
GROUP BY country
Related