Showing posts with label keys. Show all posts
Showing posts with label keys. Show all posts

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

)

how to find if index key is ASC or DESC from system tables?

There is a index: CustomerInfo_1
with keys: customerId, EnteryDate DESC
I could not find where the order of index key (i.e. whether the key is ascending or descending) is stored?
I tried system tables such as sysindexes and sysindexkeys tables. But could not find it.
Any help in this regard will be truly appreciated.

Thank you.
Regards,
Anuj GoyalWhen defining indexes, you can specify whether the data for each column is stored in ascending or descending order. If neither direction is specified, ascending is the default.

You can use INDEXKEY_PROPERTY to know the order, refer to books online for more information.