Languages
[Edit]
EN

MySQL - GROUP BY multiple columns

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to use GROUP BY statement with multiple columns in MySQL.

Quick solution:

SELECT `column1`, `column2`, `columnN`
FROM `table_name`
WHERE condition
GROUP BY `column1`, `column2`, `columnN`
ORDER BY `column_name`;

Practical example

To show how GROUP BY with multiple columns works, we will use the following table:

MySQL - example data used with GROUP BY multiple columns
MySQL - example data used with GROUP BY multiple columns
 

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will display the number of users with the same name and department_id.

Query:

SELECT `name`, `department_id`, COUNT(*)
FROM `users`
GROUP BY `name`,`department_id`;

Result:

MySQL - GROUP BY multiple columns result
MySQL - GROUP BY multiple columns result

Result explanation:

As we see, the COUNT(*) column contains the number of users with the same name and department_id. For example, there are three people named Ailisa in the department 3.

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NOT NULL,
	`surname` VARCHAR(50) NOT NULL,
	`department_id` INT(10) UNSIGNED,
    `salary` DECIMAL(15,2) NOT NULL,
	PRIMARY KEY (`id`)
);

insert_data.sql file:

INSERT INTO `users`
	( `name`, `surname`, `department_id`, `salary`)
VALUES
	('John', 'Stewart', 1, '2000.00'),
	('Chris', 'Brown', 3, '2000.00'),
	('Chris', 'Lewis', 3, '2000.00'),
	('Kate', 'Lewis', 3, '2000.00'),
	('Kate', 'Stewart', 3, '2000.00'),
	('Ailisa', 'Lewis', 3, '2000.00'),
	('Ailisa', 'Gomez', 3, '3000.00'),
	('Gwendolyn', 'James', 2, '3000.00'),
	('Simon', 'James', 2, '2000.00'),
	('Simon', 'Brown', 3, '2000.00'),
	('Simon', 'Collins', 3, '3000.00');

MySQL - Problems

MySQL - GROUP BY multiple columns
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join