postgres reorders expressions when inlining

From: Floris Van Nee <florisvannee(at)Optiver(dot)com>
To: "pgsql-bugs(at)lists(dot)postgresql(dot)org" <pgsql-bugs(at)lists(dot)postgresql(dot)org>
Subject: postgres reorders expressions when inlining
Date: 2022-12-29 10:58:35
Message-ID: fe6d0843072a480c82fa48b15eea00b1@opammb0562.comp.optiver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Hi hackers,

I recently ran into some behavior with inlining that seemed strange to me. I managed to break it down into a small reproducible example that I've added. I originally ran into it in more complicated queries that involved inlining of SQL functions instead of subqueries, but it reproduces with subqueries too so that's the example I've added. Tested on v15.

create table t1 as select a, b from generate_series(0, 5) a, generate_series(0, 10) b;
select * from (
select a, b, c
from t1
left join lateral
(
select 1 / b as c
) c on true
where b <> 0
) as o
where o.c is not null

The SELECT query leads to a division by zero. Plan:

Seq Scan on t1
Filter: (((1 / b) IS NOT NULL) AND (b <> 0))

Postgres seems to decide that it's smart to execute the "o.c is not null" check before checking if b is 0. However, this obviously leads to division by 0. In many other cases (for example not using left join lateral but instead putting the calculation straight into the SELECT of the subquery), Postgres does the right thing and checks for 0 first. Also, forcefully disabling inlining (by adding "offset 0" to the subquery for example) makes the query execute correctly.

Is it expected that Postgres reorders these expressions? I'd think that, even though Postgres decides to inline a query, it should at least evaluate the expressions of the inner-part before the outer part to avoid the division by zero.

-Floris

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Frank Reppin 2022-12-29 11:21:30 Re: BUG #17733: ERROR: could not load library "/Users/frank/postgres/postgresql-13.9/lib/postgresql/llvmjit.so": dl
Previous Message Andres Freund 2022-12-29 03:03:29 Re: BUG #17717: Regression in vacuumdb (15 is slower than 10/11 and possible memory issue)