Monday, May 4, 2009

How to find duplicate values using SQL


Assume, Table sample contains 3 rows

select * from sample;
+----+------------+
| id | Name |
+----+------------+
| 1 | xyz |
| 2 | Rajesh |
| 3 | Rajesh |
+----+------------+

Select name,count(*) from sample group by name;

The above query will group all the similar name
value into a group,count(*) will list the number
of counts for the value in the group.

+------------+----------+
| Name | count(*) |
+------------+----------+
|Rajesh | 2 |
| ABC | 1 |
+------------+----------+

Now we can able to identify the duplicate rows,
but how to list the
duplicate rows alone.


Select Name,count(*) from sample group by
name having count(*) > 1;

+------------+----------+
| Name | count(*) |
+------------+----------+
|Rajesh | 2 |
+------------+----------+
As we know duplicate rows has the count greater
than 1. So we are using the Having clause to
check which group contains the counts greater than 1

No comments:

Post a Comment