Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

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.4/5 (10 votes cast)