Description
The GROUP BY clause can be used to group rows based on column values.
- It is in conjunction (or used along) with the SELECT statement and aggregate functions.
- It must appear after the FROM and WHERE clauses, and before the ORDER BY in a SELECT statement.
Let's look at a SELECT statement that uses the GROUP BY clause to group the rows.
Table Data
Before executing any queries, consider the below data on the tables.
customer_id | customer_name | address | city | country | postal_code |
1 | Maria Anders | Obere Str. 57 | Berlin | Germany | 12209 |
2 | Fran Wilson | C/ Araquil, 67 | Madrid | Spain | 28023 |
3 | Dominique Perrier | 25, rue Lauriston | Paris | France | 75016 |
4 | Martin Blank | Via Monte Bianco 34 | Turin | Italy | 10100 |
5 | Thomas Hardy | 89 Chiaroscuro Rd. | Portland | USA | 97219 |
6 | Christina Aguilera | Gran Va, 1 | Madrid | Spain | 28001 |
7 | Hanna Moos | Forsterstr. 57 | Mannheim | Germany | 68306 |
8 | Frdrique Citeaux | 24, place Klber | Strasbourg | France | 67000 |
9 | Laurence Lebihan | 12, rue des Bouchers | Marseille | France | 13008 |
10 | Elizabeth Lincoln | 23 Tsawassen Blvd. | Tsawassen | Canada | T2F 8M4 |
Example
The below SELECT statement groups the table rows based on the country, with a count of employees against each country.
- We have used aliases to define custom output column names for the count.
SELECT country, count(*) AS customer_count
FROM customers
GROUP BY country;
After successful execution, the output contains the below data.
country | customer_count |
Canada | 1 |
France | 3 |
Germany | 2 |
Italy | 1 |
Spain | 2 |
USA | 1 |
Overall
We now understood how to create a SELECT statement with a GROUP BY clause.