CodeBlanks Logo Icon CodeBlanks

Multi-column grouping

Group by multiple columns.

Multi-column grouping

Grouping by multiple columns creates subgroups. Column order matters.

SELECT country, city, COUNT(*)
FROM customers
GROUP BY country, city;

This query counts by country and city.

country, city, COUNT(*) is selected from customers. Rows are grouped by country, city; aggregate functions are computed per group.

Multi-column grouping — details

The first column is the parent group, the second is the subgroup. Each distinct pair is a row.

For example, GROUP BY country, city gives a separate row for each city in each country: Türkiye-İzmir and Türkiye-Bursa are separate groups.

Practice Multi-column grouping

Group customers first by country then by city.

Starter code

query.sql
-- country city
SELECT country, city, COUNT(*)
FROM customers
GROUP BY country

Sample solution

query.sql
SELECT country, city, COUNT(*)
FROM customers
GROUP BY country, city;

Expected output

country  city       count
Türkiye  İstanbul   10
Türkiye  Ankara     6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Multi-column grouping: match the terms

Term Meaning
country country
city city
subgroup child
GROUP BY group

2 Add the second column

Question
SELECT country, city, COUNT(*)
FROM customers
GROUP BY country, ____;
Answer
SELECT country, city, COUNT(*)
FROM customers
GROUP BY country, city;

Explanation: GROUP BY country, city creates a separate group for each country and city combination.

3 Does order matter in multi-column GROUP BY?

  • Yes Correct answer
  • No
  • In some cases
  • Sadece COUNT'ta

Explanation: Column order sets the group hierarchy.

All lessons in Intermediate