Re: Duplicate VOLATILE predicates in a WHERE OR clause can change query results

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: wangyang25(at)otcaix(dot)iscas(dot)ac(dot)cn
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: Duplicate VOLATILE predicates in a WHERE OR clause can change query results
Date: 2026-11-23 20:01:13
Message-ID: 844264.1795464073@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

wangyang25(at)otcaix(dot)iscas(dot)ac(dot)cn writes:
> EXPLAIN (VERBOSE, COSTS OFF)
> SELECT i
> FROM generate_series(1, 200000) AS g(i)
> WHERE random() < (0.5::float8 + (i % 2)::float8 / 100::float8)
> OR random() < (0.5::float8 + (i % 2)::float8 / 100::float8);

> Expected result:

> random() is VOLATILE and can return different values on successive calls. The duplicate-OR predicate should therefore not be reduced to a single evaluation. Its result should differ from the one-call control and be consistent with two comparisons joined by OR.

I can't get excited about this. Cold reality is that if you put
volatile expressions into WHERE, you will not get predictable results
in any but the simplest single-term cases. IMV this is authorized by
the same docs you cited:

The order of evaluation of subexpressions is not defined. In
particular, the inputs of an operator or function are not
necessarily evaluated left-to-right or in any other fixed order.
...
As a consequence, it is unwise to use functions with side effects
as part of complex expressions. It is particularly dangerous to
rely on side effects or evaluation order in WHERE and HAVING
clauses, since those clauses are extensively reprocessed as part
of developing an execution plan. Boolean expressions (AND/OR/NOT
combinations) in those clauses can be reorganized in any manner
allowed by the laws of Boolean algebra.

Concretely, even if we did not de-duplicate the OR arms, we'd still
short-circuit evaluation of the OR as soon as one clause returns
true, so that the number of evaluations of random() would still be
unpredictable.

If you really need random() to be evaluated twice per row, you could
arrange that by calling it from a plpgsql function. Or maybe use
LATERAL function calls. But don't expect us to lobotomize the
optimizer and executor in service of this; we have more-useful things
to spend our limited engineering effort on.

regards, tom lane

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Álvaro Herrera 2026-11-23 21:57:52 Re: BUG #19932: `repack (concurrently)` does not work in `psql` with `AUTOCOMMIT` set to `off`
Previous Message Tor Erik Linnerud 2026-11-23 19:54:20 Re: PG 18 JIT regression: int4range hash breaks multi-key GROUP BY