1

I used a query to find a list of Primary Keys. One Primary key per each ForiegnKey in a table by using below query.

select foreignKey, min(primaryKey)
from t
group by foreignKey;

Let us say this is the result : 1,4,5

NOw I have another table - Table B that has list of all Primary keys. It has 1,2,3,6,7,8,9

I want a write a query using the above query So that I get a subset of the original query(above) that does not exist in Table B. I want 4 and 5 back with the new query.

1 Answer 1

1

Use a having clause:

select foreignKey, min(primaryKey)
from t
group by foreignKey
having min(primarykey) not in (select pk from b);

You should also be able to express this as not exists:

having not exists (select 1
                   from b
                   where b.pk = min(t.primaryKey)
                  )
Sign up to request clarification or add additional context in comments.

3 Comments

If the Table B has a couple of million records and first part of the query barely returns 10 records- Does the approach change. Is there a better option? Just curious
@Marco . . . It seems strange to me that you are only comparing the minimum id to b, but that is what you are asking for. But not exists should be fine assuming you have an index on the column in b.
Some data corruption happened. We are trying to figure out the missing data. It does not have to be min. But random would have worked too. like how you had suggested in link. I just need the foreign key to be identified- Where primary Key is missing when compared to Table B.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.