Single-column grouping
- SQL course
- Intermediate
- Lesson 25/115
- 4 min
Group by one column.
Single-column grouping
Single-column grouping is the simplest form. Each distinct value becomes a group.
SELECT city, COUNT(*)
FROM customers
GROUP BY city;This query gives the customer count per city.
city, COUNT(*) is selected from customers. Rows are grouped by city; aggregate functions are computed per group.
Single-column grouping — details
You cannot put non-grouped columns in SELECT; only the group column and aggregates.
For example, SELECT city, name FROM customers GROUP BY city fails; name is not grouped, so it is unclear which customer's name to show.
Practice Single-column grouping
Group customers by city and count.
Starter code
-- by city
SELECT city, COUNT(*)
FROM customersSample solution
SELECT city, COUNT(*)
FROM customers
GROUP BY city;Expected output
city count İstanbul 10 Ankara 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add GROUP BY
SELECT city, COUNT(*)
FROM customers
____ city;
SELECT city, COUNT(*)
FROM customers
GROUP BY city;
Explanation: GROUP BY is the right answer.
2 Can a non-grouped column appear in SELECT?
- Only in WHERE
- It can be written
- In some cases
- It cannot be written Correct answer
Explanation: Non-grouped columns cannot be in SELECT.
3 Single-column grouping: match the terms
| Term | Meaning |
|---|---|
city |
city |
COUNT |
count |
GROUP BY |
group |
single column |
simple |