ISNULL(Count(x),0) not returning 0 when null

Chris picture Chris · Jan 22, 2014 · Viewed 14.4k times · Source

I have the following code:

SELECT     FirstName, LastName,
(SELECT ISNULL(COUNT(UP1.EmailAddress), 0) AS HasEmail 
     From dbo.UserProfiles AS UP1 
     WHERE (NOT (UP1.EmailAddress IS NULL)) AND (CreatedBy = dbo.UserProfiles.UserID)
     GROUP BY CreatedBy) AS EmailEnteredCount FROM dbo.UserProfiles WHERE (IsStaff = 1)

Sample Results:

LastName EmailEnteredCount

bill NULL

Larson 51

Christie 30

parrish NULL

senac NULL

The code executes correctly with one exception, it is returning a null value when no records are found rather than the intended 0. I have also tried using coalesce to no avail.

UPDATE: This returns what I am trying to accomplish just need a cleaner solution. I really don't think I need to create a temp table just to replace a null value.

drop table #tt
                    select userid,firstname, lastname, 
                    (
                      SELECT     count(*) AS HasEmail
                      FROM         dbo.UserProfiles AS UP1
                      WHERE     (UP1.EmailAddress IS NOT NULL)AND (UP1.CreatedBy = UserProfiles.UserId) and (datecreated between @startdate and @enddate)
                      GROUP BY CreatedBy
                    ) as EmailCount
                    into #tt
                    from dbo.UserProfiles where isstaff = 1

                    select userid,firstname, lastname, ISNULL(EmailCount,0) As EmailCount from #tt

Any help would be appreciated.

Thanks, Chris

Answer

George Mastros picture George Mastros · Jan 22, 2014

You need to move the isnull function outside the correlated subquery, like this:

SELECT  FirstName, 
        LastName,
        IsNull((
            SELECT  COUNT(UP1.EmailAddress) AS HasEmail 
            From    dbo.UserProfiles AS UP1 
            WHERE   (NOT (UP1.EmailAddress IS NULL)) 
                    AND (CreatedBy = dbo.UserProfiles.UserID)
            GROUP BY CreatedBy), 0) AS EmailEnteredCount 
FROM    dbo.UserProfiles 
WHERE   (IsStaff = 1)