How to find duplicate rows with SQL

This article shows how to find duplicated rows in a database table. This is a very common beginner question. The basic technique is straightforward. I’ll also show some variations, such as how to find “duplicates in two columns” (a recent question on the #mysql IRC channel).

How to find duplicated rows

The first step is to define what exactly makes a row a duplicate of another row. Most of the time this is easy: they have the same value in some column. I’ll take this as a working definition for this article, but you may need to alter the queries below if your notion of “duplicate” is more complicated.

For this article, I’ll use this sample data:

create table test(id int not null primary key, day date not null);

insert into test(id, day) values(1, '2006-10-08');
insert into test(id, day) values(2, '2006-10-08');
insert into test(id, day) values(3, '2006-10-09');
select * from test;
id day
1 2006-10-08
2 2006-10-08
3 2006-10-09

The first two rows have the same value in the day column, so if I consider those to be duplicates, here’s a query to find them. The query uses a GROUP BY clause to put all the rows with the same day value into one “group” and then count the size of the group:

select day, count(*) from test GROUP BY day;
day count(*)
2006-10-08 2
2006-10-09 1

The duplicated rows have a count greater than one. If you only want to see rows that are duplicated, you need to use a HAVING clause (not a WHERE clause), like this:

select day, count(*) from test group by day HAVING count(*) > 1;
day count(*)
2006-10-08 2

This is the basic technique: group by the column that contains duplicates, and show only those groups having more than one row.

Why can’t you use a WHERE clause?

A WHERE clause filters the rows before they are grouped together. A HAVINGclause filters them after grouping. That’s why you can’t use a WHERE clause in the above query.

How to delete duplicate rows

A related question is how to delete the ‘duplicate’ rows once you find them. A common task when cleaning up bad data is to delete all but one of the duplicates, so you can put proper indexes and primary keys on the table, and prevent duplicates from getting into the table again.

Again, the first thing to do is make sure your definition is clear. Exactly which row do you want to keep? The ‘first’ one? The one with the largest value of some column? For this article, I’ll assume you want to keep the ‘first’ row – the one with the smallest value of the id column. That means you want to delete every other row.

Probably the easiest way to do this is with a temporary table. Especially in MySQL, there are some restrictions about selecting from a table and updating it in the same query. You can get around these, as I explain in my article How to select from an update target in MySQL, but I’ll just avoid these complications and use a temporary table.

The exact definition of the task is to delete every row that has a duplicate, except the row with the minimal value of id for that group. So you need to find not only the rows where there’s more than one in the group, you also need to find the row you want to keep. You can do that with the MIN() function. Here are some queries to create the temporary table and find the data you need to do the DELETE:

create temporary table to_delete (day date not null, min_id int not null);
insert into to_delete(day, min_id)select day, MIN(id) from test group by day having count(*) > 1;
select * from to_delete;
day min_id
2006-10-08 1

Now that you have this data, you can proceed to delete the ‘bad’ rows. There are many ways to do this, and some are better than others (see my article about many-to-one problems in SQL), but again I’ll avoid the finer points and just show you a standard syntax that ought to work in any RDBMS that supports subqueries:

delete from testwhere exists(select * from to_deletewhere to_delete.day = test.day and to_delete.min_id <> test.id)

If your RDBMS does not support subqueries, or if it’s more efficient, you may wish to do a multi-table delete. The syntax for this varies between systems, so you need to consult your system’s documentation. You may also need to do all of this in a transaction to avoid other users changing the data while you’re working, if that’s a concern.

How to find duplicates in multiple columns

Someone recently asked a question similar to this on the #mysql IRC channel:

I have a table with columns b and c that links two other tablesb and c, and I want to find all rows that have duplicates in eitherb or c.
It was difficult to understand exactly what this meant, but after some conversation I grasped it: the person wanted to be able to put unique indexes on columns b andc separately.

It’s pretty easy to find rows with duplicate values in one or the other column, as I showed you above: just group by that column and count the group size. And it’s easy to find entire rows that are exact duplicates of other rows: just group by as many columns as you need. But it’s harder to identify rows that have either a duplicated b value or a duplicated c value. Take the following sample table, which is roughly what the person described:

create table a_b_c(a int not null primary key auto_increment,b int,c int
);
insert into a_b_c(b,c) values (1, 1);
insert into a_b_c(b,c) values (1, 2);
insert into a_b_c(b,c) values (1, 3);
insert into a_b_c(b,c) values (2, 1);
insert into a_b_c(b,c) values (2, 2);
insert into a_b_c(b,c) values (2, 3);
insert into a_b_c(b,c) values (3, 1);
insert into a_b_c(b,c) values (3, 2);
insert into a_b_c(b,c) values (3, 3);

Now, you can easily see there are some ‘duplicate’ rows in this table, but no two rows actually have the same tuple {b, c}. That’s why this is a bit more difficult to solve.

Queries that don’t work

If you group by two columns together, you’ll get various results depending on how you group and count. This is where the IRC user was getting stumped. Sometimes queries would find some duplicates but not others. Here are some of the things this person tried:

select b, c, count(*) from a_b_c
group by b, c
having count(distinct b > 1)or count(distinct c > 1);

This query returns every row in the table, with a COUNT(*) of 1, which seems to be wrong behavior, but it’s actually not. Why? Because the > 1 is inside theCOUNT(). It’s pretty easy to miss, but this query is actually the same as

select b, c, count(*) from a_b_c
group by b, c
having count(1)or count(1);

Why? Because (b > 1) is a boolean expression. That’s not what you want at all. You want

select b, c, count(*) from a_b_c
group by b, c
having count(distinct b) > 1or count(distinct c) > 1;

This returns zero rows, of course, because there are no duplicate {b, c} tuples. The person tried many other combinations of HAVING clauses and ORs and ANDs, grouping by one column and counting the other, and so forth:

select b, count(*) from a_b_c group by b having count(distinct c) > 1;
b count(*)
1 3
2 3
3 3

Nothing found all the duplicates, though. What I think made it most frustrating is that it partially worked, making the person think it was almost the right query… perhaps just another variation would get it…

In fact, it’s impossible to do with this type of simple GROUP BY query. Why is this? It’s because when you group by one column, you distribute like values of the othercolumn across multiple groups. You can see this visually by ordering by those columns, which is what grouping does. First, order by column b and see how they are grouped:

a b c
7 1 1
8 1 2
9 1 3
10 2 1
11 2 2
12 2 3
13 3 1
14 3 2
15 3 3

When you order (group) by column b, the duplicate values in column c are distributed into different groups, so you can’t count them with COUNT(DISTINCT c) as the person was trying to do. Aggregate functions such as COUNT() only operate within a group, and have no access to rows that are placed in other groups. Similarly, when you order by c, the duplicate values in column b are distributed into different groups. It is not possible to make this query do what’s desired.

Some correct solutions

Probably the simplest solution is to find the duplicates for each column separatelyand UNION them together, like this:

select b as value, count(*) as cnt, 'b' as what_colfrom a_b_c group by b having count(*) > 1unionselect c as value, count(*) as cnt, 'c' as what_colfrom a_b_c group by c having count(*) > 1;
value cnt what_col
1 3 b
2 3 b
3 3 b
1 3 c
2 3 c
3 3 c

The what_col column in the output indicates what column the duplicate value was found in. Another approach is to use subqueries:

select a, b, c from a_b_cwhere b in (select b from a_b_c group by b having count(*) > 1)or c in (select c from a_b_c group by c having count(*) > 1);
a b c
7 1 1
8 1 2
9 1 3
10 2 1
11 2 2
12 2 3
13 3 1
14 3 2
15 3 3

This is probably much less efficient than the UNION approach, and will show every duplicated row, not just the values that are duplicated. Still another approach is to do self-joins against grouped subqueries in the FROM clause. This is more complicated to write correctly, but might be necessary for some complex data, or for efficiency:

select a, a_b_c.b, a_b_c.c
from a_b_cleft outer join (select b from a_b_c group by b having count(*) > 1) as b on a_b_c.b = b.bleft outer join (select c from a_b_c group by c having count(*) > 1) as c on a_b_c.c = c.c
where b.b is not null or c.c is not null

Any of these queries will do, and I’m sure there are other ways too. If you can use UNION, it’s probably the easiest.

SQL:find duplicate rows -- using group or having相关推荐

  1. SQL错误Duplicate column name 'NAME'名字重复应使用别名

    SQL错误Duplicate column name 'NAME'名字重复应使用别名 <select id="getCurrentAndInformation" result ...

  2. Ubuntu上配置SQL Server Always On Availability Group

    下面简单介绍一下如何在Ubuntu上一步一步创建一个SQL Server AG(Always On Availability Group),以及配置过程中遇到的坑的填充方法. 目前在Linux上可以搭 ...

  3. Java java.sql.SQLSyntaxErrorException:Duplicate column name ‘xxx‘问题解决

    问题描述: java.sql.SQLSyntaxErrorException: Duplicate column name 'username'; bad SQL grammar []; 问题分析: ...

  4. Linux 上配置 SQL Server Always On Availability Group

    SQL Server Always On Availability Group 配置 步骤: 配置三台 Linux 集群节点 创建 Availability Group 配置 Cluster Reso ...

  5. ERROR Executor: Exception in task 0.0 in stage 1.0 (TID 1) java.sql.BatchUpdateException: Duplicate

    sparksql把JDBC 从关系型数据库中读取数据的方式创建 DataFrame报错: 20/08/26 15:29:37 ERROR Executor: Exception in task 0.0 ...

  6. SQL语句之分组查询--GROUP BY(group by)

    SQL语句之分组查询–GROUP BY(group by) 语法 select 聚合函数,列(要求出现在group by的后面)from 表where 筛选条件group by 分组的列表order ...

  7. Java java.sql.SQLIntegrityConstraintViolationException:Duplicate entry ‘xx‘ for key ‘xx.PRIMARY‘问题解决

    问题描述: Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '111' for key 'users ...

  8. SQL分组多列统计(GROUP BY后按条件分列统计)

    最近遇到一个问题,需要对一张表做统计,这个统计有什么特别之处值得我记录了下来呢?大家知道SQL中聚合函数GROUP BY的结果一般为一列,即多个值通过聚合函数运算统计到一起,但是如何将不同条件的值统计 ...

  9. SQL优化一例:GROUP BY的语句

    SQL语句: select t.type, count(t.id) as todo_count from mc_job_form t where t.state = '2' and t.customs ...

最新文章

  1. DPI — Application Assurance — Overview
  2. Hibernate的关联关系映射
  3. redis源码之sds
  4. zcmu1540(二分)
  5. 16 导出pcb各网络的布线长度_PCB原理图常见错误分析
  6. 神奇的事情,不同进程监听同一个端口,居然都成功
  7. ListView.setOnItemClickListener 点击无效
  8. 【Qt教程】2.2 - Qt5 布局管理器(水平、垂直、栅格布局)、弹簧、设计一个登陆界面
  9. python ---ConfigParser
  10. JavaScript 函数 对象 数组
  11. Python :h5py 如何对dataset进行重新赋值?
  12. 新东方 词根词缀 excel_14张图搞定高中英语词汇常见词缀词根!
  13. c语言写的电脑开关机代码,只需要几行代码制作电脑开关机控制软件
  14. 20120912新工作感想
  15. 微信分享与支付开发详解
  16. B站动态自检方法1 bilibili应用自检
  17. 参考file-convert-util工具,实现doc,docx,html,md,pdf,png转换
  18. JPA(Java Persistence API,Java持久化API)
  19. java+vue实现词云生成+展示(kumo+echarts-wordcloud )
  20. 计算机显示器不亮灯,电脑液晶显示器指示灯不亮是为什么?

热门文章

  1. Android 自定义控件之腾讯安全卫士扫描
  2. Web-IM前端解决方案
  3. 微軟平台的管理專家 - Microsoft Operations Manager (MOM)
  4. Ubuntu 源列表
  5. struts -Tiles介绍
  6. Ext---CheckBoxGroup的取值和赋值
  7. staticextension 上提供值时引发了异常_干!一张图整理了 Python 所有内置异常
  8. 天津大学计算机在线作业答案,天大19秋《计算机应用基础》在线作业二【满分答案】...
  9. George and Job(动态规划)
  10. 树的距离(牛客网树上主席树+dfs序)