Q

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
inner
  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 first published in March 2007

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

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.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close