Compare Data Between Two Tables in SQL Server

I had explained the TableDiff in one of my previous posts.

In this post, let us see how to do a simple data comparison without using the TableDiff utility. Remember that this is only for small tables with less columns.

To create some sample data, let us take the Customers table of the Northwind database and create a duplicate of it

SELECT * INTO CustomersTemp FROM Customers

Now change some data in the Customers Temp table by using the following query

UPDATE CustomersTemp

SET City = 'Bern'




UPDATE CustomersTemp

SET Country = 'France'


It's now time to execute our query. I am comparing just 4 columns for changes. Remember as I said, use it on small tables with lesser columns:

SELECT table1.*, table2.*

FROM Customers AS table1

FULL JOIN CustomersTemp AS table2

ON table2.CustomerID = table1.CustomerID


table1.CompanyName <> table2.CompanyName OR

table1.ContactName <> table2.ContactName OR

table1.Country <> table2.Country OR

table1.City <> table2.City

Running this query returns the two rows that do not match each other.

Know a better and simpler T-SQL that can do this? Share it here please!

About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

No comments: