EN
MySQL - GROUP BY statement
0 points
In this article, we would like to show you how to use GROUP BY
statement in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT `column1`, `column2`, `columnN`
2
FROM `table_name`
3
WHERE condition
4
GROUP BY `column_name`
5
ORDER BY `column_name`;
To show how the GROUP BY
statement works, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will display the number of users in each country descending.
Query:
xxxxxxxxxx
1
SELECT COUNT(`name`) AS `number of users`, `country`
2
FROM `users`
3
GROUP BY `country`
4
ORDER BY COUNT(`name`) DESC;
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`country` VARCHAR(15) NOT NULL,
5
PRIMARY KEY (`id`)
6
)
7
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `country`)
3
VALUES
4
('Tom', 'Poland'),
5
('Chris', 'Spain'),
6
('Jack', 'Spain'),
7
('Kim', 'Vietnam'),
8
('Marco', 'Italy'),
9
('Kate', 'Spain'),
10
('Nam', 'Vietnam');