Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison Query to Compare Two SQL Server Tables [duplicate]

I would like to know how to compare two different database table records. What I mean is I will compare two database tables which may have different column names but same data. But one of them may have more records than the other one so I want to see what the difference is between those two tables. To do that how to write the sql query ? FYI : these two databases are under the same SQL Server instance.

Table1
------+---------
|name |lastname|
------+---------
|John |rose    |
------+---------
|Demy |Sanches |
------+---------

Table2
------+----------
|name2|lastname2|
------+----------
|John |rose     |
------+----------
|Demy |Sanches  |
------+----------
|Ruby |Core     |
------+----------

Then when after comparing table 1 and table 2, it should return Ruby Core from Table2.

like image 842
Tarik Avatar asked Nov 26 '22 22:11

Tarik


2 Answers

Select * from Table1
Except
Select * from Table2

It will show all mismatch records between table1 and table2

like image 57
Fahad Sattar Avatar answered Jun 03 '23 15:06

Fahad Sattar


Late answer but can be useful to other readers of this thread

Beside other solutions, I can recommend SQL comparison tool called ApexSQL Data Diff.

I know you'd prefer the solution not based on the software, but for other visitors, who may want to do this in an easier way, I strongly suggest reading this article: http://solutioncenter.apexsql.com/how-to-compare-sql-server-database-tables-with-different-names/

The article explains how to use the Object mapping feature in ApexSQL Data Diff, which is particularly useful in situations where two tables share the same name, but their column names are different.

To handle such a case - each column pair needs to be mapped manually in order for the data stored within them to be included when comparing SQL database tables for differences.

like image 31
Derrick Whitacker Avatar answered Jun 03 '23 15:06

Derrick Whitacker