How to write "not in ()" sql query using join

SqlSql ServerTsqlNotin

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

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.

Solution 2 - Sql

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

Solution 3 - Sql

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
    )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmanuView Question on Stackoverflow
Solution 1 - SqlQuassnoiView Answer on Stackoverflow
Solution 2 - SqlAducciView Answer on Stackoverflow
Solution 3 - SqlRob PallerView Answer on Stackoverflow