Q. What is the difference between count(0), count(1), and count(*) in MySQL/SQL?


Ans. The difference in “count(<whatever>)” is mostly if you have

count(<fixed value>)

versus

  1. count(<expression>) 

select count(<fixed value>) - as long as it isn’t a literal NULL - ends up being the same as count(*)And no, 0 isn’t special; select count(0) is the same as select count(1).

select count(<expression>) is actually interesting. It adds 1 for each row where <expression> evaluates to non-NULL, and 0 otherwise. So, you can do the following:

  1. select count(somecol) from sometab; 

returns the total count of records where somecol IS NOT NULL

  1. select count(if(somecol > 50, 1, NULL)) from sometab; 

returns the total count of records where somecol is > 50

The above may seem silly, until you realize that you can use count() multiple times, ie

  1. select count(if(somecol > 50, 1, NULL)), 
  2. count(if(othercol between <date1> and <date2>, 1, NULL)), 
  3. count(if(yetanothercol between col17 and col19, 1, NULL), 
  4. count(if(col21 in ('foo','bar','baz','blah'),1,NULL)),  
  5. ... and hundreds of others ... 
  6. from sometab; 

(yes, the if() function is MySQL-specific, but you can implement similar logic with case/when, etc)

This is an easy, highly-performant way to do reports that involve a whole bunch of counting with different counting conditions without needing to do numerous passes through the table; the added “count()s” after the first one are basically “free” in terms of performance.

Comments

Popular posts from this blog

SQL Assignment – Module 4

SQL Assignments TABLE

SQL Assignment – Module 1