Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Unexpected division by zero using SUM

This query (minimal reproducible example):

WITH t as (
    SELECT 3 id, 2 price, 0 amount
)
SELECT 
    CASE WHEN amount > 0 THEN
        SUM(price / amount)
    ELSE
        price
    END u_price
FROM t
GROUP BY id, price, amount

on PostgreSQL 9.4 throws

division by zero

Without the SUM it works.

How is this possible?

like image 963
nmck Avatar asked Aug 27 '18 16:08

nmck


1 Answers

I liked this question and I turned for help to these tough guys :

The planner is guilty:

A CASE cannot prevent evaluation of an aggregate expression contained within it, because aggregate expressions are computed before other expressions in a SELECT list or HAVING clause are considered

More details at https://www.postgresql.org/docs/10/static/sql-expressions.html#SYNTAX-EXPRESS-EVAL

like image 78
cetver Avatar answered Oct 31 '22 04:10

cetver