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

Find all The Rows Where Any Of The Columns Is Null Or Zero Or Both

From Wiki

Jump to: navigation, search

How can you quickly without writing a bunch of OR statements determince if any columns have a NULL value, a value of 0 or if the value is 0 or NULL? To test for NULL is very easy, you just concatenate the columns since NULL + anything else is always NULL. Okay that also depends on a setting.

Run this

  1. SET CONCAT_NULL_YIELDS_NULL ON
  2.     SELECT NULL + '1' --NULL
  3.      
  4.     SET CONCAT_NULL_YIELDS_NULL OFF
  5.     SELECT NULL + '1' --1


As you can see if CONCAT_NULL_YIELDS_NULL is OFF then the result is 1

Now take a look at this


  1. SET CONCAT_NULL_YIELDS_NULL ON
  2.     SELECT NULL + 1 --NULL
  3.      
  4.      
  5.      
  6.     SET CONCAT_NULL_YIELDS_NULL OFF
  7.     SELECT NULL + 1 --NULL


So with numeric values it behaves differently. Either way by default CONCAT_NULL_YIELDS_NULL is set to on To test for NULLS or zeroes you use NULLIF To test for zeros you can combine COALESCE and NULLIF

Here is the code which shows all of that

  1. CREATE TABLE #test(column1 INT,column2 VARCHAR(4),column3 FLOAT)
  2.      
  3.     INSERT #test VALUES(2,'2',2)
  4.     INSERT #test VALUES(0,'1',0)
  5.     INSERT #test VALUES(null,'1',0)
  6.     INSERT #test VALUES(1,null,0)
  7.     INSERT #test VALUES(0,'1',null)
  8.     INSERT #test VALUES(null,null,null)


  1. --Any column is Null
  2.     SELECT * FROM #test
  3.     WHERE column1 + column2+column3 IS null


Output

NULL 1 0.0
1 NULL 0.0
0 1 NULL
NULL NULL NULL



  1. --Any column is Null or zero
  2.     SELECT * FROM #test
  3.     WHERE NULLIF(column1,0) + NULLIF(column2,0)+NULLIF(column3,0) IS null


Output

0 1 0.0
NULL 1 0.0
1 NULL 0.0
0 1 NULL
NULL NULL NULL



  1. --Any column is zero
  2.     SELECT * FROM #test
  3.     WHERE NULLIF(COALESCE(column1,1),0) +
  4.     NULLIF(COALESCE(column2,1),0)+
  5.     NULLIF(COALESCE(column3,1),0) IS null


Output

0 1 0.0
NULL 1 0.0
1 NULL 0.0
0 1NULL


  1. DROP TABLE #test


Contributed by: --SQLDenis 03:08, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Handy tricks

184 Rating: 1.2/5 (6 votes cast)