Click here to Skip to main content
15,884,472 members
Articles / Database Development / SQL Server
Tip/Trick

Ways to Compare and Find Differences for SQL Server Tables

Rate me:
Please Sign up or sign in to vote.
4.76/5 (9 votes)
18 Aug 2016CPOL 16.6K   14   2
Sometimes, we need to compare 2 tables to see what was changed. This tip shows you 2 different ways to compare data.

Introduction

Sometimes, we need to compare 2 tables to see what was changed. This tip shows you 2 different ways to compare data.

Preparation

Let's create two tables with identical structure and add some data.

The code might be like this:

SQL
CREATE TABLE [dbo].[#1](
 [id] [nchar](10) NOT NULL,
 [type] [nchar](10) NULL,
 [cost] [money] NULL,)
GO
insert into [dbo].[#1] values
('001','1','40'),
('002','2','80'),
('003','3','120'),
('004','4','160'),
('004','5','160')
GO

CREATE TABLE [dbo].[#2](
 [id] [nchar](10) NOT NULL,
 [type] [nchar](10) NULL,
 [cost] [money] NULL,)
GO
insert into [dbo].[#2] values
('001','1','40.05'),
('002','2','80'),
('003','6','120'),
('004','4','160'),
('004','5','160.01')
GO

The easiest way to see the differences between two tables is using of except clause. Code could be like this:

SQL
SELECT ID, TYPE, COST FROM #1
EXCEPT
SELECT ID, TYPE, COST FROM #2

SELECT ID, TYPE, COST FROM #2
EXCEPT
SELECT ID, TYPE, COST FROM #1

Code below can show the differences in a more friendly format:

SQL
SELECT ID, TYPE, COST FROM
(
    SELECT ID, TYPE, COST FROM #1
    UNION ALL
    SELECT ID, TYPE, COST FROM #2
) A
GROUP BY ID, TYPE, COST
HAVING COUNT(*) <> 2

UNION ALL lets us combine all records from both tables. Condition 'HAVING COUNT(*) <> 2 hides identical records.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerTable comparison using SQL Pin
dornech19-Aug-16 2:24
dornech19-Aug-16 2:24 
GeneralRe: Table comparison using SQL Pin
Michael Ecklin19-Aug-16 3:53
Michael Ecklin19-Aug-16 3:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.