What is GROUP BY?
- SQL course
- Intermediate
- Lesson 24/115
- 4 min
Group rows by a column.
What is GROUP BY?
GROUP BY groups rows by a column. One row is produced per group.
SELECT category, COUNT(*)
FROM products
GROUP BY category;This query gives the product count per category.
category, COUNT(*) is selected from products. Rows are grouped by category; aggregate functions are computed per group.
What is GROUP BY? — details
GROUP BY works with aggregate functions. COUNT, SUM, AVG are applied per group.
For example, SELECT category, COUNT(*) FROM products GROUP BY category gives the number of products in each category on one row.
Practice What is GROUP BY?
Group products by category and count.
Starter code
-- count per category
SELECT category, COUNT(*)
FROM productsSample solution
SELECT category, COUNT(*)
FROM products
GROUP BY category;Expected output
category count Elektronik 3 Kitap 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does GROUP BY do?
- Filters
- Deletes rows
- Groups rows Correct answer
- Sorts them
Explanation: GROUP BY groups rows by a shared value.
2 Add GROUP BY
SELECT category, COUNT(*)
FROM products
____ category;
SELECT category, COUNT(*)
FROM products
GROUP BY category;
Explanation: GROUP BY is the right answer.
3 What is GROUP BY: match the terms
| Term | Meaning |
|---|---|
GROUP BY |
group |
COUNT |
count |
SUM |
sum |
AVG |
average |