Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if all table rows are equal

Tags:

sql

sql-server

There are two tables with identical structure.
Let's assume the number of rows in both is equal.
how would you check if all rows are equal? Is there any faster way than comparing every column value of a given row with the same id in both tables?

like image 490
Greg Avatar asked Jul 14 '11 17:07

Greg


2 Answers

Try this:

SELECT * FROM table1
EXCEPT
SELECT * FROM table2

If anything is returned then they are not equal.

like image 199
Abe Miessler Avatar answered Sep 30 '22 13:09

Abe Miessler


Abe's answer is correct, but only if they have the same number of rows. (I misread the question when I wrote my original response "condemning" his answer.) If table1 may be a subset of (a larger) table2 or vice versa, I would try:

if 
(
not exists ( select * from table1
             except
             select * from table2
           )
and
not exists ( select * from table2
             except
             select * from table1
           )
)

This gives true if they are the same, and false if they are different.

like image 28
Eric Brown Avatar answered Sep 30 '22 14:09

Eric Brown