Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 341
manu Avatar asked Apr 15 '11 12:04

manu


People also ask

Can we use not in join?

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).

How do you write not in condition in SQL?

Overview. The SQL Server NOT IN operator is used to replace a group of arguments using the <> (or !=) operator that are combined with an AND. It can make code easier to read and understand for SELECT, UPDATE or DELETE SQL commands.

How replace NOT IN subquery with join?

Equivalent Join For above subquery :SELECT l.id,l.name FROM tleft l LEFT JOIN tright r ON l.id = r. t_left_id WHERE r. t_left_id IS NULL; AND clause will be applied during the JOIN and WHERE clause will be applied after the JOIN .


1 Answers

This article:

  • NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: SQL Server

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.

like image 171
Quassnoi Avatar answered Sep 22 '22 18:09

Quassnoi