Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find missing values on the same column of two tables

Suppose you have two tables in a SQL Server database with the same schema for both tables. I want to compare a single column on both tables and find the values that are missing in table1 but are in table2. I've been doing this manually in Excel with a macro after I've gotten a distinct list in each query, but it would be less work if I had a query. How can I find the missing records via T-SQL? I'd like to do this for the following data types: datetime, nvarchar & bigint.

SELECT DISTINCT [dbo].[table1].[column1]
FROM [dbo].[table1]
ORDER BY [dbo].[table1].[column1] DESC

SELECT DISTINCT [dbo].[table2].[column1]
FROM [dbo].[table2]
ORDER BY [dbo].[table2].[column1] DESC
like image 535
MacGyver Avatar asked Mar 22 '13 15:03

MacGyver


People also ask

How do you find matching columns in two tables?

In this approach you can join the two tables on the primary key of the two tables and use case statement to check whether particular column is matching between two tables. Select case when A. col1 = B. col1 then 'Match' else 'Mismatch' end as col1_cmpr, case when A.


2 Answers

There are several ways you can do this...

LEFT JOIN:

SELECT DISTINCT t2.column1
FROM dbo.table2 t2
LEFT JOIN dbo.table1 t1
  ON t2.Column1 = t1.Column1
WHERE t1.Column1 IS NULL

NOT EXISTS:

SELECT DISTINCT t2.column1
FROM dbo.table2 t2
WHERE NOT EXISTS (
  SELECT 1
  FROM dbo.table1 t1
  WHERE t1.column1 = t2.column1
)

NOT IN:

SELECT DISTINCT t2.column1
FROM dbo.table2 t2
WHERE t2.column1 NOT IN (
  SELECT t1.column1
  FROM dbo.table1 t1
)

There are some slight variations in the behavior and efficiency of these approaches... based mostly on the presence of NULL values in columns, so try each approach to find the most efficient one that gives the results you expect.

like image 146
Michael Fredrickson Avatar answered Sep 19 '22 21:09

Michael Fredrickson


SELECT DISTINCT [dbo].[table2].[column1]
FROM [dbo].[table2]
except
SELECT DISTINCT [dbo].[table1].[column1]
FROM [dbo].[table1]

All the values of column1 in Table2 that are not present in column1 of Table1

like image 44
jerrylagrou Avatar answered Sep 20 '22 21:09

jerrylagrou