0

I am trying to compare two tables in two separate databases (same instance) for a new data extract The tables have around 4 millions rows and due to how they've been extracted are not in the same order in each table, as they are just staging tables (there is no PKs).

I have tried using (select * from table 1 Except select * from table 2) UNION ALL (select * from table 2 Except select * from table 1) however this results in around 10 millions rows so is not working as expected.

I would guess the results should be around a few thousand.

0

2 Answers 2

0

If the records are unique in each table you can do something like this:

SELECT COUNT(*), FIELD1, FIELD2, FIELD3 FROM (
SELECT FIELD1, FIELD2, FIELD3 FROM TABLE1 
UNION ALL 
SELECT FIELD1, FIELD2, FIELD3 FROM TABLE2) SUBSEL
GROUP BY FIELD1, FIELD2, FIELD3
HAVING COUNT(*) = 1
0

First of all you have to define your primary key - one or several fields what will unique identify the record. All fields as primary key is possible but not recommended

Second, you have to decide what you mean as 'compare':

  • records exists in first table but not in second
  • records exists in both tables but has difference in non primary key fields
  • records exists in the second table only
2
  • The problem with defining a primary key is none of the columns can be made unique there are 14 columns in total, there are some like reference / surname etc. that would normally be ideally for a PK but there are duplicates because if all 14 columns are not exact match the system enters a new row. It is not our data we extract it from a 3rd party so don't have control of the input system
    – QueryQuirk
    Commented Oct 3, 2023 at 7:13
  • Since your query returned ALL records in both datasets I guess you missed field order. Try to use field names instead of star. Try to limit queries with WHERE clause instead of all records. Your query looks correct
    – SergeyA
    Commented Oct 3, 2023 at 19:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.