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

Testing for Null Values

From Wiki

Jump to: navigation, search

How do you test for NULL values? First create this table

  1. CREATE TABLE testnulls (ID INT)
  2. INSERT INTO testnulls VALUES (1)
  3. INSERT INTO testnulls VALUES (2)
  4. INSERT INTO testnulls VALUES (null)


People new to SQL will usually try to run the following query

  1. SELECT * FROM testnulls WHERE ID = NULL

As you can see nothing is returned. However there is a setting that you can use to make it work

Run this

  1. SET ANSI_NULLS OFF

Now run the query again

  1. SELECT * FROM testnulls WHERE ID = NULL

See, it works. However this is NOT recommended and as a matter of fact this has been deprecated So let's set it back to the default.

  1. SET ANSI_NULLS ON

This is how you properly test for NULLS

  1. SELECT * FROM testnulls WHERE ID IS NULL

You could also use the functions ISNULL or COALESCE with a non existing value in the table, this however is not recommended because a function on the left side of the operator will result in non optimized query (scan)

  1. SELECT * FROM testnulls WHERE ISNULL(ID,-66666) = -66666
  2. SELECT * FROM testnulls WHERE COALESCE(ID,-66666) = -66666


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


Part of SQL Server Programming Hacks

Section NULLS

114 Rating: 3.0/5 (17 votes cast)