Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing values of 2 tables and listing the rows that are different

This question is in the same vein as this question, but just slightly different.

I have 2 tables, TableA and TableB where TableB is really just a backup of TableA, the only real difference is that TableB has an "ACTION" column that indicates the action that had been taken in TableA. For now I am ignoring that column (although ideally I would want it appended to the final results, so please feel free to suggest on that too :D )

I want to compare the two tables and get the rows from each table that are different. I've used Jeff's SQL Server Blog - The shortest, fastest, and easiest way to compare two tables in SQL Server: UNION ! example to create a query, however, it returns only the rows from TableB that are different.

What is the recommended approach?

Note: the code is exactly like the example in the second link, so I won't post any of it here

like image 974
Emmanuel F Avatar asked Jun 22 '11 15:06

Emmanuel F


People also ask

How do you compare data between two tables?

Compare two tables by using joins. To compare two tables by using joins, you create a select query that includes both tables. If there is not already an existing relationship between the tables on the fields that contain the corresponding data, you create a join on the fields that you want to examine for matches.

How do I compare two tables in Excel for differences?

Open the workbooks you want to compare. Go to the View tab, Window group, and click the View Side by Side button. That's it!

How do I compare values in two tables in SQL?

Comparing the Results of the Two Queries Let us suppose, we have two tables: table1 and table2. Here, we will use UNION ALL to combine the records based on columns that need to compare. If the values in the columns that need to compare are the same, the COUNT(*) returns 2, otherwise the COUNT(*) returns 1.

How do I compare two row values?

Say you want to compare the two rows above and highlight cells where the rows don't match (Columns D, G, and H) in red. Select the data range you want to compare, and in the Ribbon, go to Home > Conditional Formatting > Highlight Cells Rules > Duplicate Values.


1 Answers

This will give you everything in A that's not in B

select * from tableA
Except
select * from tableB

and vice-versa

select * from tableB
Except
select * from tableA

Edit: Joined this way:

(select * from tableA
Except
select * from tableB)
union all
(select * from tableB
Except
select * from tableA)
like image 166
Bob Probst Avatar answered Sep 20 '22 11:09

Bob Probst