Find the total number of customers from each country using GROUP BY
Expt. No.28
Page No.56
Customers per country
Aim
To find the number of customers from each country in a CUSTOMER table (customer ID, customer name, country) using GROUP BY.
Concepts used
Queries
USE shop;SELECT country, COUNT(*) FROM customer GROUP BY country;
A marked line continues the line above it. In your file, write it on the same line.
Table used
Table: customer
+-----+--------+---------+ | cid | cname | country | +-----+--------+---------+ | 1 | Arjun | India | | 2 | Emma | UK | | 3 | Liam | USA | | 4 | Priya | India | | 5 | Noah | USA | | 6 | Kiran | India | | 7 | Olivia | UK | +-----+--------+---------+
Output
mysql> USE shop;
Database changed
mysql> SELECT country, COUNT(*) FROM customer GROUP BY country;
+---------+----------+
| country | COUNT(*) |
+---------+----------+
| India | 3 |
| UK | 2 |
| USA | 2 |
+---------+----------+
3 rows in set
✓ Printed by running this query set, not typed by hand.
Result
GROUP BY made one group per country: India has 3 customers, and the UK and the USA have 2 each.
Viva voce: what the examiner may ask
01What does GROUP BY do?
It puts rows with the same value in a column into one group, so an aggregate function gives one result per group.
02Which columns can be shown with GROUP BY?
The grouped column and aggregate functions.
03How do you show only countries with more than 2 customers?
Add HAVING COUNT(*) > 2.
Variations for the lab test
- Display the countries in descending order of the number of customers.
- Display only the countries with exactly 2 customers.
- Count the customers whose name starts with a given letter (using LEFT()).
! Common mistake Writing
WHERE COUNT(*) > 2 is an error; conditions on groups go in HAVING.