Thread

  1. Re: BUG #19358: Short circuit optimization exists in generic plan but missed in custom plan

    Tom Lane <tgl@sss.pgh.pa.us> — 2025-12-17T21:37:24Z

    PG Bug reporting form <noreply@postgresql.org> writes:
    > ... So why the short
    > circuit optimization applied in the prepared update (with a generic plan)
    > but not in the normal update (with a custom plan).
    
    Const-folding doesn't stop just because the current part of the
    expression tree might not be reached at runtime.  EXPLAIN shows
    that your generic plan is
    
    regression=# explain verbose EXECUTE prepare_query('', '[-993693027,1525305818]'::int4range,
    '[-168306621,-163656947)'::int4range);
                                                 QUERY PLAN                                              
    -----------------------------------------------------------------------------------------------------
     Update on public.t3  (cost=0.00..47.40 rows=0 width=0)
       ->  Seq Scan on public.t3  (cost=0.00..47.40 rows=157 width=38)
             Output: $1, ctid
             Filter: ((t3.c0 = t3.c0) OR ((t3.c0 >= (t3.c0 || (($2 - $3))::text)) AND (t3.c0 <= t3.c0)))
    (4 rows)
    
    So the "t3.c0 = t3.c0" condition will be found to be true and we don't
    reach the right-hand side of the OR.  However, if $2 and $3 are
    replaced by constants, the planner will attempt to reduce the range
    difference to a constant at plan time.
    
    There have been previous discussions about how this sometimes leads to
    unintuitive failures, but I don't see how we could skip const-folding
    without huge performance penalties in some cases.  In any case, we
    clearly document that you can't rely on specific execution order of
    boolean expressions.  You will not find anything in our docs promising
    left-to-right evaluation of ORs.
    
    			regards, tom lane