GROUP BY in CTE causes ELSE in outer query to be prematurely evaluated - Mailing list pgsql-bugs

From Björn Kautler
Subject GROUP BY in CTE causes ELSE in outer query to be prematurely evaluated
Date
Msg-id CAKChYSo2n2_q_XtvO-3ow+Q0dSuWdzwydLbtr3Q12X65bqhL=g@mail.gmail.com
Whole thread
Responses Re: GROUP BY in CTE causes ELSE in outer query to be prematurely evaluated
Re: GROUP BY in CTE causes ELSE in outer query to be prematurely evaluated
List pgsql-bugs
Hi

If you have the query

WITH FOO AS (
         SELECT 0 AS GROUPING
     )
SELECT CASE
    WHEN GROUPING >= 0 THEN 'non-negative'
    ELSE CAST((1 / 0) AS VARCHAR)
END
FROM FOO;

it works successfully, having the ELSE as a safeguard against having coded a bug, having forgotten a WHEN branch, so it fails fast.

So if you have

WITH FOO AS (
         SELECT -1 AS GROUPING
     )
SELECT CASE
    WHEN GROUPING >= 0 THEN 'non-negative'
    ELSE CAST((1 / 0) AS VARCHAR)
END
FROM FOO;

it fails with a division by zero error.

But if you have the query

WITH FOO AS (
         SELECT 0 AS GROUPING
         GROUP BY 1
     )
SELECT CASE
    WHEN GROUPING >= 0 THEN 'non-negative'
    ELSE CAST((1 / 0) AS VARCHAR)
END
FROM FOO;

then it always fails with division by zero error, even though the result should still be 'non-negative'.

Cheers
Björn

pgsql-bugs by date:

Previous
From: PG Bug reporting form
Date:
Subject: BUG #19425: Parametric settings in collation not working in rule syntax
Next
From: Laurenz Albe
Date:
Subject: Re: GROUP BY in CTE causes ELSE in outer query to be prematurely evaluated