Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding duplicates across 2 tables 1

Status
Not open for further replies.

CHUMPY

Programmer
Oct 8, 2002
37
GB
Hi,

I know this should be basic SQL but have been struggling on this one!

I have two identical tables T1 and T2 with two fields which are composite primary keys. If I wish to insert only records from T2 into T1 that don't already exist in T1 how can I do it?

e.g.

T1 T2

A B A B
1 2 1 2
2 3 2 3
3 4 8 9



What will be the SQL to insert only the third record (8 9) from T2 into T1?

Thanks

Gareth
 
Hi


First I create the tables

Code:
create table t1 (A number(2), B number(2));
create table t2 (a number(2), b number(2));

Now your data:

Code:
insert into t1 values( 1, 2);
insert into t1 values( 2, 3);
insert into t1 values( 3, 4);

insert into t2 values( 1, 2);
insert into t2 values( 2, 3);
insert into t2 values( 8, 9);

and now the insert statement:

Code:
insert into t1
  select * from t2
  where not exists (select 1 from t1
                      where t1.a = t2.a
                      and   t1.b = t2.b
                    );

or this statement

Code:
insert into t1                    
  select * from t2 where (a,b) not in (select a,b from t1);

Depending on the amount of data the first is faster because Oracle doesn’t generate data between joins.


Regards
Allan
Icq: 346225948
 
Hi,

Thanks to both of you, I was trying something similar to Allan just seem to be having one of those days!

I wasn't aware of the merge command, wish I was. Just finished writing a tool to combine multiple schemas into one..... that command looks like I could of saved a bit of time!!!!

Thanks

Gareth
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top