HAVING
The HAVING clause is similar to the WHERE clause with the exception that it is only used
to filter after aggregation has occurred. In the previous sections, we looked at using GROUP BY, here we implement the
same queries as before but we then add
a HAVING clause for post aggregation selection
HAVING filter less than
The following query will compute the average profit by product category and return categories of product whose avg_profit is less than 6000
SELECT category,
round(avg((price - cost)*stock_quantity),2) as avg_profit
FROM products
GROUP BY 1
HAVING avg((price - cost)*stock_quantity) < 6000;
Notice that the HAVING clause is always placed after the GROUP BY because it filters the results of a computation.
HAVING filter greater than
Let's take a look at the opposite of the earlier query by reversing the condition
SELECT
category,
round(avg((price - cost)*stock_quantity), 2) as avg_profit
FROM products
GROUP BY 1
HAVING avg((price - cost) * stock_quantity) > 6000;