Wednesday, March 7, 2012

How to find missing records from tables involving composite primary keys

Table 1

Code Quarter
50000226
50000227
50000228
50000228.5
50000229

Table 2

Code Qtr
50000226
50000227

I have these two identical tables with the columns CODE & Qtr being COMPOSITE PRIMARY KEYS

Can anybody help me with how to compare the two tables to find the records not present in Table 2

That is i need this result

Code Quarter
50000228
50000228.5
50000229

I have come up with this solution

select scrip_cd,Qtr,scrip_cd+Qtr from Table1 where
scrip_cd+Qtr not in (select scrip_cd+qtr as 'con' from Table2)

i need to know if there is some other way of doing the same

Thanks in Advance

Jacx

You can use the following query too...

Select
A.Code,
A.Quarter
From
[Table 1] A
Left Outer Join [Table 2] B on A.Code = B.Code And A.Quarter = B.Quarter
Where
B.Code is NULL

|||

Using NOT EXISTS is the fastest way to solve your problem. Use query below:

select t1.scrip_cd, t1.Qtr

from Table1 as t1

where not exists(

select * from Table2 as t2

where t2.scrip_cd = t1.scrip_cd and t2.Qtr = t1.Qtr

)

No comments:

Post a Comment