68

Could some one please provide how to write following sql query using joins. I do not want use not in as well as if possible I would like to replace where condition as well.

SELECT d1.Short_Code
FROM domain1 d1
WHERE d1.Short_Code NOT IN (
  SELECT d2.Short_Code
  FROM Domain2 d2
)

I am using SQL Server 2008

3 Answers 3

95

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

Sign up to request clarification or add additional context in comments.

13 Comments

@Quassnoi, could you please provide the efficient way way writing the same query using either "NOT NULL" and/or "NOT EXISTS"
@Elan: your original query is just nice. Just create the indexes on short_code in both tables.
@Aducci: I'm assuming nothing, I'm just rewriting the original query.
@Aducci: LEFT JOIN is less efficient indeed. The question was "how to rewrite without NOT IN" — here's how.
DUDE you are SUPER AWESOME :) Thanks for the above query i was stuck somewhere like hell and You are a SAVIOR :)
|
22
SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

Comments

8

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

4 Comments

What difference would NOT EXISTS make?
Instead of an outer join or a complex OR operation (with the NOT IN clause) the optimizer should use the equivalent of an exclusion merge join between the two tables.
the optimizer will build exactly same plan for both NOT IN and NOT EXISTS (as long as short_code is not nullable). There will be no "complex OR operations".
Didn't realize that. Behavior in Teradata is slightly different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.