miercuri, 2 iunie 2010

SQL query for finding duplicates

I've noticed this problem among persons who seemed to have some experience on querying data bases.
Detect duplicates in a table. For example we have he table TABLE1 with columns C1, C2, C3 and we need all the entries that have duplicate C1 value or duplicate combination C1,C2.

One of the solution is this:

select * from TABLE1 t where 1>(select count(*) from TABLE1 t1 where t.C1 = t1.C1);

select * from TABLE1 t where 1>(select count(*) from TABLE1 t1 where t.C1 = t1.C1 and t.C2 = t1.C2);

Same syntax is used for DB2, Informix, Oracle.

Un comentariu:

  1. a colleague of mine told me this the queries above don't work, because he needed something similar and they didn't help him: neither he convinced me that his needs were the same, neither he gave me his solution.

    But if you find mistakes I am open to fix them.

    RăspundețiȘtergere