Solved

To compare uncommon values in two tables

Posted on 2010-11-24
3
717 Views
Last Modified: 2012-05-10
Hi,
Suppose we have two tables both have a column CODE. Now we want to know what are the values that appear in CODE column of table 1 but are not present in CODE column of table 2. What should be the TSQL to find that?
0
Comment
Question by:nkapur
  • 2
3 Comments
 
LVL 29

Accepted Solution

by:
Nightman earned 50 total points
ID: 34208551
Give this a bash.

SELECT * FROM Table1 as t1
WHERE
  NOT EXISTS
  (
    SELECT * FROM Table2 as t2 WHERE t2.CODE=t1.CODE
  )
0
 
LVL 26

Expert Comment

by:wilcoxon
ID: 34209271
Nightman has the right of it.  I would also recommend using select 1 rather than select * in the sub-query (usually very minimal performance impact but can be substantial if Table2 has wide rows).

SELECT * FROM Table1 as t1
WHERE
  NOT EXISTS
  (
    SELECT 1 FROM Table2 as t2 WHERE t2.CODE=t1.CODE
  )
0
 
LVL 29

Expert Comment

by:Nightman
ID: 34210375
normally wilcoxon would be correct about the select *, but in reality this a boolean expression and the value of * isn't evaluated, only the condtions.

You could even do the following with no divide by zero error:

SELECT * FROM Table1 as t1
WHERE
  NOT EXISTS
  (
    SELECT 1/0 FROM Table2 as t2 WHERE t2.CODE=t1.CODE
  )
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question