'aggregation inside "case when" - What's the executing order?

Why does this simple query result in a "division by zero" Error?

select 
case when b > 0 then sum(a / b) end
from (values (1,1),(2,1),(1,0),(2,0)) t (a,b)
group by b

I would expect the output:

case
3
NULL

The only explanation I have is that postgres calculates the sum before doing the grouping and evaluating the case.



Solution 1:[1]

Use NULLIF() to avoid the problem, you don't need a CASE for this:

SELECT  
     SUM(a / NULLIF(b,0))
FROM 
    (values (1,1),(2,1),(1,0),(2,0)) t (a,b)
GROUP BY b
ORDER BY 1; -- first (and only) column

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank Heikens