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

后端 未结 9 1922

I was recently asked this question in an interview. I tried this in mySQL, and got the same results(final results). All gave the number of rows in that particular table. Can

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 02:24

    Since the expression 1 is a constant expression, they should always produce the same result, but the implementations might differ as some RDBMS might check whether 1 IS NULL for every single row in the group. This is still being done by PostgreSQL 11.3 as I have shown in this article.

    I've benchmarked queries on 1M rows doing the two types of count:

    -- Faster
    SELECT count(*) FROM t;
    
    -- 10% slower on PostgreSQL 11.3
    SELECT count(1) FROM t;
    

    One reason why people might use the less intuitive COUNT(1) could be that historically, it was the other way round.

提交回复
热议问题