Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL how to check that two tables has exactly the same data?

Tags:

sql

I have two tables TableA and TableB which have the same format of columns, which means both tables have the columns

A B C D E F  

where A and B are the primary keys.

How do I write an SQL query to check if TableA and TableB (which have identical primary keys) contain exactly the same values in every column?

It means that these two tables have exactly the same data.

like image 924
nikky Avatar asked Jan 05 '11 08:01

nikky


People also ask

How do you find common data in two tables in SQL?

If you are using SQL Server 2005, then you can use Intersect Key word, which gives you common records. If you want in the output both column1 and column2 from table1 which has common columns1 in both tables.

How would you see common data between 2 tables?

The SQL intersect operator allows us to get common values between two tables or views. The following graphic shows what the intersect does. The set theory clearly explains what an intersect does. In mathematics, the intersection of A and B (A ∩ B) is the set that contains all elements of A that also belong to B.

How do I find duplicate records in two tables in SQL?

Use the INNER JOIN function to find duplicates that exist in multiple tables. Sample syntax for an INNER JOIN function looks like this: SELECT column_name FROM table1 INNER JOIN table2 ON table1. column_name = table2.


2 Answers

You should be able to "MINUS" or "EXCEPT" depending on the flavor of SQL used by your DBMS.

select * from tableA minus select * from tableB 

If the query returns no rows then the data is exactly the same.

like image 110
dietbuddha Avatar answered Oct 12 '22 23:10

dietbuddha


Using relational operators:

SELECT * FROM TableA UNION  SELECT * FROM TableB EXCEPT  SELECT * FROM TableA INTERSECT SELECT * FROM TableB; 

Change EXCEPT to MINUS for Oracle.

Slightly picky point: the above relies on operator precedence, which according to the SQL Standard is implementation dependent, so YMMV. It works for SQL Server, for which the precedence is:

  1. Expressions in parentheses
  2. INTERSECT
  3. EXCEPT and UNION evaluated from left to right.
like image 26
onedaywhen Avatar answered Oct 13 '22 00:10

onedaywhen