Does COUNT(*) always return a result?

Click Upvote picture Click Upvote · Mar 31, 2010 · Viewed 14.3k times · Source

If I run a query such as:

SELECT COUNT(*) as num FROM table WHERE x = 'y'

Will it always return a result, even when the query doesn't match any record? Or do I need to validate and make sure a row is returned as the result?

Answer

gbn picture gbn · Mar 31, 2010

Yes, because it's an aggregate and returns zero. Unless you add GROUP BY in which case no result because there is no group...

MAX/SUM etc would return NULL unless you add GROUP BY then no rows. Only COUNT returns a number for no results

Edit, a bit late: SUM would return NULL like MAX

Edit, May 2013: this applies to all main RDBMS. I guess as per the ANSI standard