Problem solve Get help with specific problems with your technologies, process and projects.

Compare two tables for anomalies

Is there any syntax in SQL that will take data from one table, compare it to another table, and return any anomalies that exist?

I'm trying to find a syntax that will take data from one table, compare it to another table, and return any anomalies...

that exist. Is this possible?

Most definitely possible.

select A.pk
     , A.col1, B.col1
     , A.col2, B.col2
     , A.col3, B.col3
  from table_one as A
  join table_two as B
    on B.pk = A.pk
 where A.col1 <> B.col1 
    or A.col2 <> B.col2 
    or A.col3 <> B.col3 
union all
select A.pk
     , A.col1, null
     , A.col2, null
     , A.col3, null
  from table_one as A
left outer
  join table_two as B
    on B.pk = A.pk
 where B.pk is null
union all
select B.pk
     , null, B.col1
     , null, B.col2
     , null, B.col3
  from table_two as B
left outer
  join table_one as A
    on A.pk = B.pk
 where A.pk is null

The inner join, with its WHERE conditions, returns rows which exist in both tables but which have at least one column different. Then the two outer joins, with their WHERE conditions, return rows which exist in one table but not the other. The results of these three subqueries are combined with UNION ALL to return all anomalies.

This was last published in March 2007

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.