Best sellers
- SQL course
- Intermediate
- Lesson 44/115
- 5 min
Find the best-selling product with HAVING.
Best seller
To find the best-selling product you use GROUP BY product and HAVING.
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
HAVING SUM(amount) > 1000;This query returns products selling over 1000.
product, SUM(amount) AS total is selected from sales. Rows are grouped by product; aggregate functions are computed per group. HAVING SUM(amount) > 1000 runs after grouping and drops groups that fail the condition.
Best seller — details
HAVING runs after groups are formed. ORDER BY can put the highest total first.
For example, ORDER BY total DESC LIMIT 5 returns the five best-selling products.
Practice Best seller
Find products with totals over 1000 using HAVING SUM(amount) > 1000.
Starter code
-- best seller
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY productSample solution
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
HAVING SUM(amount) > 1000;Expected output
product total Laptop 3500 Telefon 2100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you find the best seller?
- WHERE + COUNT
- DISTINCT
- GROUP BY + HAVING Correct answer
- JOIN
Explanation: Group by product and filter with HAVING.
2 Add HAVING
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
____ SUM(amount) > 1000;
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
HAVING SUM(amount) > 1000;
Explanation: HAVING SUM(amount) > 1000 keeps products whose total sales exceed 1000.
3 Best sellers: match the terms
| Term | Meaning |
|---|---|
GROUP BY |
group |
HAVING |
filter |
SUM |
sum |
ORDER BY |
sort |