Comparing Column Values in T-SQL
Okay… so here's the scenario. I have two different tables in a SQL Database, where I need to compare both tables, and find all values in Table B that do not exist in Table A. There are two ways to do this. One with a JOIN, and one with a "NOT EXISTS" Clause:
Method 1:
SELECT b.[ColumnName]
FROM DBName.dbo.tblB b
LEFT OUTER JOIN DBName.dbo.tblA a
ON b.[ColumnName] = a.[ColumnName]
WHERE a.[ColumnName] IS NULL
GROUP BY b.[ColumnName];
Method 2:
SELECT b.[ColumnName]
FROM DBName.dbo.tblB b
WHERE NOT EXISTS
(
SELECT *
FROM DBName.dbo.tblA
WHERE a.[ColumnName] = b.[ColumnName]
)
GROUP BY b.[ColumnName];
I hope this helps someone! My malformed queries have been driving me nuts all week…
Comments
Anonymous
January 01, 2003
Excellent !! I've been wracking my brains for ages trying to figure out how to do this (new to SQL). I actually have to work out what does not exist in one table when compared to 2 others, but taking the above and allowing for the extra table has solved my problem. I had played around with LEFT OUTER JOIN, but did not consider the comparison with NULL !! Many thanks.Anonymous
June 10, 2015
US home solar power system capacity increase of 76% over last year, to 437 megawatts (MW) ,Solar Batterieshttp://www.poweroak.net the nation's new generating capacity, more than half of which is a photovoltaic power generation. The report shows that a quarter of the US solar power capacity by 1.3 gigawatts (GW), the sixth consecutive quarterly increase of over 1 GW. The total annual installed capacity is expected to reach 7.9 GW, Solar Power Peneratorhttp://www.poweroak.net , Solar Power Pack http://www.poweroak.net representing an increase of 27%.
The report predicts that by 2016 solar power will meet the electricity needs of about 800 million households in the United States to offset 45 million metric tons of carbon emissions, equivalent to removing 10 million cars. energy storage systemhttp://www.poweroak.net/energy-storage-system-c-1.htmlAnonymous
June 23, 2015
The comment has been removedAnonymous
June 23, 2015
The comment has been removedAnonymous
June 23, 2015
The comment has been removedAnonymous
June 23, 2015
The comment has been removedAnonymous
June 23, 2015
The comment has been removedAnonymous
June 23, 2015
The comment has been removed