EN
MySQL - find duplicated values in multiple columns
0 points
In this article, we would like to show you how to find duplicated values in multiple columns in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT
2
`column1`, COUNT(`column1`),
3
`column2`, COUNT(`column2`),
4
`columnN`, COUNT(`columnN`)
5
FROM
6
`table_name`
7
GROUP BY
8
`column1`,
9
`column2`,
10
`columnN`
11
HAVING
12
(COUNT(`column1`) > 1) AND
13
(COUNT(`column2`) > 1) AND
14
(COUNT(`columnN`) > 1);
To show how to find duplicated values in multiple columns, 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 duplicated users and countries where:
name_quantity
- number of duplicated names,country_quantity
- number of duplicated countries.
Note:
This works only when both
name
andcountry
in a row are duplicated.
Query:
xxxxxxxxxx
1
SELECT
2
`name`, COUNT(`name`) AS 'name_quantity',
3
`country`, COUNT(`country`) AS 'country_quantity'
4
FROM
5
`users`
6
GROUP BY
7
`name`,
8
`country`
9
HAVING
10
(COUNT(`name`) > 1) AND
11
(COUNT(`country`) > 1);
Result:

Note:
Notice that
Chris
user bothname_quantity
andcountry_quantity
equals2
because one user is from a different country.
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
`email` VARCHAR(100) NOT NULL,
5
`country` VARCHAR(15) NOT NULL,
6
PRIMARY KEY (`id`)
7
)
8
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `email`, `country`)
3
VALUES
4
('Tom', 'tom1@email.com', 'Poland'),
5
('Tom', 'tom2@email.com', 'Poland'),
6
('Tom', 'tom3@email.com', 'Poland'),
7
('Kim', 'kim1@email.com', 'Vietnam'),
8
('Kim', 'kim2@email.com', 'Vietnam'),
9
('Chris', 'chris1@email.com', 'Spain'),
10
('Chris', 'chris2@email.com', 'Spain'),
11
('Chris', 'chris3@email.com', 'USA');