Finding the correct subquery for the "not in" condition

Finding the correct subquery for the "not in" condition

Can you please see if the following query is correct? If not, could you provide the right syntax for a subquery which contains the "not in" condition?

select bid from bp where bid not in (select bid from bp_hist)l

    Requires Free Membership to View

    When you register, my team of editors will also send you resources covering Linux administration and management; integration and interoperability between Linux, Windows and Unix; securing Linux and mixed-platform environments; and migrating to Linux.

    Margie Semilof, Editorial Director

    By submitting your registration information to SearchEnterpriseLinux.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchEnterpriseLinux.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Let us first create table bp and insert a few rows into it:

  1. create table bp (bid int not null, bname varchar(30) null)
  2. go
  3. insert bp values (1, 'a')
  4. insert bp values (2,'b')
  5. insert bp values (3,'c')
  6. go

  7. (1 row affected)
    (1 row affected)
    (1 row affected)
  8. insert bp values (4,'d')
  9. go

  10. (1 row affected)

Now create a historical table bp_hist:

  1. select * into bp_hist from bp where bid <= 3
  2. go

  3. (3 rows affected)

Now try the first syntax:

  1. select bid from bp where bid not in (select bid from bp_hist)
  2. go

  3. bid
    -----------
    4

As you can see, the syntax is correct. However, a more efficient way of doing this query is to use the NOT EXISTS clause in the query as shown below:

  1. select bid from bp a where not exists(select 1 from bp_hist b where a.bid = b.bid)
  2. go

  3. bid
    -----------
    4

This was first published in December 2005