Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

NOT IN and NULLs

From Wiki

Jump to: navigation, search

When you use NOT IN with a table which contains NULL values you can run into a problem First create these two tables

  1. CREATE TABLE testnulls (ID INT)
  2.     INSERT INTO testnulls VALUES (1)
  3.     INSERT INTO testnulls VALUES (2)
  4.     INSERT INTO testnulls VALUES (null)
  5.  
  6.     CREATE TABLE testjoin (ID INT)
  7.     INSERT INTO testjoin VALUES (1)
  8.     INSERT INTO testjoin VALUES (3)
  9.     INSERT INTO testjoin VALUES (null)


Now run the following code

  1. SELECT * FROM testjoin WHERE ID NOT IN(SELECT ID FROM testnulls)

See what happens? Nothing is returned

Now run this

  1. SELECT * FROM testjoin WHERE ID NOT IN(SELECT ID FROM testnulls WHERE ID IS NOT NULL)

That worked. You can also use NOT EXISTS and LEFT JOIN

LEFT JOIN

  1. SELECT j.* FROM testjoin j
  2.     LEFT OUTER JOIN testnulls n ON n.ID = j.ID
  3.     WHERE n.ID IS NULL


NOT EXISTS

  1. SELECT * FROM testjoin j
  2.     WHERE NOT EXISTS (SELECT n.ID
  3.     FROM testnulls n
  4.     WHERE n.ID = j.ID)


Contributed by: --SQLDenis 16:35, 30 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section NULLS

119 Rating: 1.9/5 (8 votes cast)