steventnorris
steventnorris

Reputation: 5896

Find duplicates between two SQL tables

I have two tables (Table1 and Table2) with the same primary keys, lets say Key1 and Key2. What I need to do is seperate the records in Table1 into two groups, the duplicates (records found in Table2) and the non-duplicates. I know I could use the below, but that seems bloated and repetetive. Is there a trimmer way to do this, possibly with a single call?

SELECT Key1, Key2 FROM Table1 WHERE Key1 IN (SELECT Key1 FROM Table2) AND Key2 IN (SELECT Key2 FROM Table2);
SELECT Key1, Key2 FROM Table1 WHERE Key1 NOT IN (SELECT Key1 FROM Table2) AND Key2 NOT IN (SELECT Key2 FROM Table2);

;

This call is being made from a C# ASP.NET codebehind page.

Upvotes: 0

Views: 1169

Answers (2)

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171421

This query does a left outer join to ensure all records from table1 are returned. It joins on Table2, and if there are no matches, than any columns in Table2 will be NULL for that row. This behavior is used in a CASE statement to set a flag telling where the Table1 row exists in Table2 or not:

select t1.*,
    case when t2.Key1 is null then 'false' else 'true' end as IsDuplicate
from Table1 t1
left outer join Table2 t2 on t1.Key1 = t2.Key1
    and t1.Key2 = t2.Key2

You can then filter in your application based on the IsDuplicate column.

Upvotes: 3

Ali Tarhini
Ali Tarhini

Reputation: 5358

Check the new upsert statement in SQL2008 Upsert in SQL2008

Upvotes: 0

Related Questions