HiveBrain v1.2.0
Get Started
← Back to all entries
principleMinor

Optimizing a compare query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
comparequeryoptimizing

Problem

Suppose I have two tables, A and B, and I know that size(A) = size(B). I want to confirm that the data in both tables is the same in three given columns, suppose they are X, Y, and Z (there are no keys on the table).

For that, I would do:

SELECT COUNT(*) FROM
     (
        Select
            X, Y, Z
        From
            A
     )
     MINUS
     (
        Select
            X, Y, Z
        From
            B
     )


Now, I really don't need to know count(*) value, as long as there is one mismatch between the data, i.e. values tuple exists in A but not in B, I know that the tables are not identical. Is there a way for me to say this in SQL? I.e. as soon as MINUS encounters one mismatched value, return a value from a query indicating that?

Thanks!

Solution

Not sure how such a query should be optimized for Oracle, when no indexes are available but here's another rewriting. It will not calculate the number of mismatching tuples but will stop searching when it finds one:

SELECT 1
FROM dual
WHERE EXISTS
     (
        Select
            X, Y, Z
        From
            A
     MINUS
        Select
            X, Y, Z
        From
            B
     ) ;


SQL-Fiddle shows a similar performance for all the provided answers, as the two tables have to be fully scanned in the worst case.

Rolando's and Narendra's queries show different execution time (sometimes better, sometimes worse), I think because of the HASH JOIN used.

There may be different results with bigger tables and with fewer or more matches between the two tables. (the test were done with only a few K rows).

Code Snippets

SELECT 1
FROM dual
WHERE EXISTS
     (
        Select
            X, Y, Z
        From
            A
     MINUS
        Select
            X, Y, Z
        From
            B
     ) ;

Context

StackExchange Database Administrators Q#22857, answer score: 4

Revisions (0)

No revisions yet.