GROUP BY with aggregates
- SQL course
- Intermediate
- Lesson 27/115
- 4 min
Use COUNT, SUM and friends with groups.
GROUP BY and aggregates
With GROUP BY you apply COUNT, SUM, AVG to each group.
SELECT category, SUM(price)
FROM products
GROUP BY category;This query gives the total price per category.
category, SUM(price) is selected from products. Rows are grouped by category; aggregate functions are computed per group.
GROUP BY and aggregates — details
One aggregate row per group is produced. You can use AVG, MIN, MAX instead of SUM.
For example, SUM(price) gives each category's total value, while MAX(price) gives the price of the most expensive product in it.
Practice GROUP BY and aggregates
Compute the total price per category with SUM(price).
Starter code
-- category total
SELECT category,Sample solution
SELECT category, SUM(price)
FROM products
GROUP BY category;Expected output
category sum Elektronik 1500 Kitap 200
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is applied to each group?
- WHERE
- An aggregate function Correct answer
- JOIN
- DISTINCT
Explanation: Aggregate functions apply to each group.
2 Add SUM
SELECT category, ____(price)
FROM products
GROUP BY category;
SELECT category, SUM(price)
FROM products
GROUP BY category;
Explanation: SUM(price) adds up the prices in each category.
3 GROUP BY with aggregates: match the terms
| Term | Meaning |
|---|---|
SUM |
sum |
AVG |
average |
MIN |
minimum |
MAX |
maximum |