Filtering Aggregate Results
April 3, 2018
Filtering Aggregate Results
In SQL, the HAVING
clause is used to filter aggregate results as the WHERE
clause cannot be used with aggregate functions.
We will be using the classicmodels
database, which you can download from mysqltutorial for this article.
The Products Table
The products
table contains data about the products available. Below, you will find a subset of the columns and rows in the table.
productCode | productName | productLine |
---|---|---|
S10_1678 | 1969 Harley Davidson Ultimate Chopper | Motorcycles |
S10_1949 | 1952 Alpine Renault 1300 | Classic Cars |
S10_2016 | 1996 Moto Guzzi 1100i | Motorcycles |
S10_4698 | 2003 Harley-Davidson Eagle Drag Bike | Motorcycles |
S10_4757 | 1972 Alfa Romeo GTA | Classic Cars |
The Having Clause
We want to find the product lines that have at least 15 items in the catalog. This can be accomplished using the aggregate function COUNT
and the HAVING
clause.
SELECT
productLine,
COUNT(productLine)
FROM
products
GROUP BY
productLine
HAVING
COUNT(productLine) > 15
ORDER BY
COUNT(productLine) ASC;
productLine | COUNT(productLine) |
---|---|
Vintage Cars | 24 |
Classic Cars | 38 |