Tuesday, September 14, 2010

SQL COUNT( NULLIF( .. ) ) blew my mind


Using the SQL GROUP BY clause is really awesome. It makes gathering data "about" the data very easy. Sometimes, though, when you group data, not only do you want to count the number of records in a given group, you want to count the number of records in a group with a given property.
This is something that is not as easy.

I wanted to count the number of certain types of people and simple

Select count(personID) from people where condition='True' 

kept on returning "NULL" for certain rows.

And thats when I met NULLIF...

NULLIF() is pretty bad ass. If you have not used it, it takes two arguments and works such that if the two arguments are equal in value, it returns NULL, otherwise, it just returns the first argument it was passed. So, for instance, NULLIF( 1, 1 ) would return NULL, but NULLIF( 1, 0 ) would return 1.
Now, how does NULLIF() help us? It helps us because the SQL COUNT() aggregate does NOT count NULL values. This is HUGE.

My SQL query now simply becomes

Select COUNT(NULLIF([PERSONID], 0)) from people where condition='True' 

How freakin' cool is that?!? When I randomly tried this one day and it worked, it blew my mind. Now, I work in MS SQL Server. I don't know if the NULLIF() function is standard. If is not, then, that's probably why your database was free :) (I'm just messing with you...)

Note: Please do not use "group by" with NULLIF. It keeps returning NULL regardless in that case.

No comments: