Ask the Expert

Performing a NOT IN without a subquery

Is there a way to emulate the functionality of this without a subquery:

SELECT a, b, c
  FROM tblFOO
 WHERE tblFOO.id NOT IN 
       ( SELECT id
           FROM tblBAR)

If the operator was IN instead of NOT IN, the solution could easily be done with a SELECT DISTINCT and a JOIN. But, the NOT IN seems to be a completely different animal.


    Requires Free Membership to View

The way to do this is to use an outer join. When matching rows in an outer join, the database will assign NULLs to all the columns from the table which did not have a matching row.

For example, consider

tblFOO        tblBAR
id a b c      id d e
 1 A B C       1 D E
 2 P Q R       
 3 X Y Z       3 J K 
 4 L M N       4 S T
 5 W X Y

When doing a left outer join of these tables on the id column, the database will insert NULL into all tblBAR columns for any rows of tblFOO which don't have a match -- including the id column. In the above example, this would be for the rows in the result set where tblFOO.id is 2 and 5. So the SQL you want that is equivalent to the NOT IN syntax is

SELECT tblFOO.a, tblFOO.b, tblFOO.c
  FROM tblFOO LEFT OUTER JOIN tblBAR 
    ON tblFOO.id = tblBAR.id
 WHERE tblBAR.id IS NULL

Notice that you are only SELECTing columns from tblFOO, while testing the id from tblBAR in the WHERE clause.

For More Information

  • What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
  • The Best SQL Web Links: tips, tutorials, scripts, and more.
  • Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
  • Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
  • Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

This was first published in April 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: