Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare rows from 2 tables that have composite primary keys?

Tags:

sql

sql-server

Here's the scenario:

I have 2 tables with data, one is the 2009 version and the other is the 2010 version. The primary key for each of the tables is a composite key. I know there is a different number of rows in each one and I need to find out the differences.

Typically, in the "normal" primary key set-up, I would just look for primary key values NOT IN the list of primary keys from the other table. But I don't know how to do this with a composite primary key (or even if it's possible).

So, how can I compare the rows from these two tables?


EDIT: More specifically, I am trying to find the difference between the tables, rather than the rows in common

like image 486
cdeszaq Avatar asked Jan 26 '26 20:01

cdeszaq


1 Answers

Just make a full outer join with condition based on your composite keys:

select t09.*, t10.*
from table2009 as t09
  full outer join table2010 as t10
    on t09.k1 = t10.k1 and t09.k2 = t10.k2 and ...

If you only wish to see unmatched rows (the difference) in result set, then filter them within the where clause:

where t09.k1 is null or t10.k1 is null
like image 167
BorisOkunskiy Avatar answered Jan 29 '26 08:01

BorisOkunskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!