aggregate of an empty result set

后端 未结 4 1663
一向
一向 2021-02-13 19:17

I would like the aggregates of an empty result set to be 0. I have tried the following:

SELECT SUM(COALESCE(capacity, 0))
  FROM objects
 WHERE null IS NOT NULL;         


        
4条回答
  •  余生分开走
    2021-02-13 19:47

    Just do this:

    SELECT COALESCE( SUM(capacity), 0)
    FROM objects
    WHERE null IS NOT NULL;
    

    By the way, COALESCE inside of SUM is redundant, even if capacity is NULL, it won't make the summary null.

    To wit:

    create table objects
    (
        capacity int null
    );
    
    insert into objects(capacity) values (1),(2),(NULL),(3);
    
    select sum(capacity) from objects;
    

    That will return a value of 6, not null.

    And a coalesce inside an aggregate function is a performance killer too, as your RDBMS engine cannot just rip through all the rows, it has to evaluate each row's column if its value is null. I've seen a bit OCD query where all the aggregate queries has a coalesce inside, I think the original dev has a symptom of Cargo Cult Programming, the query is way very sloooowww. I removed the coalesce inside of SUM, then the query become fast.

提交回复
热议问题