Hash a ScalarArrayOpExpr whose array is fixed for one execution

Поиск
Список
Период
Сортировка
Искать

Hash a ScalarArrayOpExpr whose array is fixed for one execution

Hi hackers,

Since PG 14 (50e17ad281) the executor can evaluate "col = ANY (array)"
with a hash table instead of a linear scan, but only when the array is a
Const.  Every parameterised form stays on the O(rows * N) path:

  col = ANY ($1)                       -- Param, generic/cached plan
  col IN ($1, ..., $N)                 -- ArrayExpr of Params
  col = ANY ($1::int[])                -- ArrayCoerceExpr
  col = ANY (string_to_array($1, ',')) -- FuncExpr

These are what drivers emit (JDBC setArray, psycopg "= ANY(%s)", asyncpg)
and what anything that expands an IN list into bind placeholders produces.
With a cached generic plan the list arrives as a Param and is never
hashed; a one-off custom plan folds it to a Const and is fine -- which is
why the slowdown tends to appear only after a statement has run a few
times.  The PG 14 thread named the non-Const case as future work,
deferred "from fear that we may slow down cases where the expression is
evaluated only once".

The attached patch does that.  It hashes any array argument the planner
can prove is fixed for the whole execution: no Vars, no volatile
functions, no aggregate/grouping/window functions, no sub-selects, and no
Params other than PARAM_EXTERN.  For such an array the executor compiles
it as an independent sub-expression, evaluates it once on the first row,
builds the hash table, and reuses it.  MIN_ARRAY_SIZE_FOR_HASHED_SAOP is
still enforced, now against the run-time element count; a shorter array
falls back to the existing linear ExecEvalArrayCompareInternal().  A
standalone ExprState (a PL/pgSQL "simple expression", reused across calls
with different parameters) keeps the linear path -- the "one execution"
proof needs an execution boundary it does not have.

Not covered, because the array is not fixed for the execution: a Var (new
array per row), a volatile function (per-row by definition), an
aggregate/grouping/window value (per group/frame/row, and only evaluable
inside its owning node), a sub-select, or a PARAM_EXEC (correlated /
nestloop-inner).  These stay linear.

Diffstat: 5 backend files, ~360 lines, plus regression tests; no new GUC,
syntax, or catalog change (as 50e17ad281).

Performance
-----------
Release build, no LLVM, generic plan forced, warm cache, one Ryzen 7
4800H laptop.  Seq scan, "SELECT count(*) FROM t WHERE v = ANY($1)",
1,000,000 rows, median of 9:

    N       master      patched
    6       59 ms       57 ms    (below threshold: linear both)
    9       65 ms       50 ms
   40      150 ms       52 ms
  100      297 ms       52 ms
 1000     2494 ms       51 ms

Patched is flat in N once hashed.  "IN ($1,...,$N)": 3.6x at N=9, 12x at
N=60.  No change on paths that stay linear (N < 9, literal IN, pgbench).

Single evaluation -- the PG 14 concern.  Plan built and run once, fresh
connection:

  rows   N     master      patched
     1   40    0.025 ms    0.028 ms
     1  200    0.023 ms    0.035 ms   (+12 us, worst seen)
  1000  100    0.316 ms    0.085 ms

Break-even is around 10 rows; worst case is +12 us to build a 200-entry
hash for a one-row scan.

Open question
------------
cost_qual_eval charges the hashed cost for an opaque stable array using
estimate_array_length()'s default guess, which slightly over-estimates
startup for an array that turns out short at run time.  I have left that
for a follow-up; happy to fold in a fix if reviewers prefer.

Possible follow-ups (kept out of scope so the bind-parameter win does not
depend on new machinery): an uncorrelated ARRAY(SELECT ...) becomes an
InitPlan whose PARAM_EXEC never changes -- execution-stable, and only the
planner needs to recognise it; and a PARAM_EXEC array on a nestloop inner
side is fixed per rescan, so it could be hashed once per rescan given a
cost gate and rescan-aware invalidation of the cached table.

The patch is v1, based on master (base-commit line included).

[1] https://www.postgresql.org/message-id/flat/CAAaqYe8x62%2B%3Dwn0zvNKCj55tPpg-JBHzhZFFc6ANovdqFw7-dA%40mail.gmail.com

Regards,
Linden Lance

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
David Geier <geidav.pg@gmail.com>
Дата:
Hi Linden!

> Since PG 14 (50e17ad281) the executor can evaluate "col = ANY (array)"
> with a hash table instead of a linear scan, but only when the array is a
> Const.  Every parameterised form stays on the O(rows * N) path:
> 
>   col = ANY ($1)                       -- Param, generic/cached plan
>   col IN ($1, ..., $N)                 -- ArrayExpr of Params
>   col = ANY ($1::int[])                -- ArrayCoerceExpr
>   col = ANY (string_to_array($1, ',')) -- FuncExpr
> 
> These are what drivers emit (JDBC setArray, psycopg "= ANY(%s)", asyncpg)
> and what anything that expands an IN list into bind placeholders produces.
> With a cached generic plan the list arrives as a Param and is never
> hashed;

That's indeed a pretty severe limitation that would be great to remove:
Today, anything that doesn't use the database in the most
straightforward doesn't profit from hashed IN.

> one-off custom plan folds it to a Const and is fine -- which is
> why the slowdown tends to appear only after a statement has run a few
> times.  The PG 14 thread named the non-Const case as future work,
> deferred "from fear that we may slow down cases where the expression is
> evaluated only once".

Why would that be? This "problem" also exists for the const case,
doesn't it? If we evaluate the IN only once, then it's always cheaper to
iterate over it instead of first creating a hash map. Or what am I missing?

We could make the choice of using the hashed SAOP or not depend on the
estimated number of rows. But given that we don't do anything like that
for the const case, I'm thinking we should do the same for the non-const
case.

> The attached patch does that.  It hashes any array argument the planner
> can prove is fixed for the whole execution: no Vars, no volatile
> functions, no aggregate/grouping/window functions, no sub-selects, and no
> Params other than PARAM_EXTERN.  For such an array the executor compiles
> it as an independent sub-expression, evaluates it once on the first row,
> builds the hash table, and reuses it.  MIN_ARRAY_SIZE_FOR_HASHED_SAOP is
> still enforced, now against the run-time element count; a shorter array
> falls back to the existing linear ExecEvalArrayCompareInternal().  A
> standalone ExprState (a PL/pgSQL "simple expression", reused across calls
> with different parameters) keeps the linear path -- the "one execution"
> proof needs an execution boundary it does not have.
> 
> Not covered, because the array is not fixed for the execution: a Var (new
> array per row), a volatile function (per-row by definition), an
> aggregate/grouping/window value (per group/frame/row, and only evaluable
> inside its owning node), a sub-select, or a PARAM_EXEC (correlated /
> nestloop-inner).  These stay linear.
> 
> Diffstat: 5 backend files, ~360 lines, plus regression tests; no new GUC,
> syntax, or catalog change (as 50e17ad281).

The patch is relatively big. How about splitting out the refactorings
(replacing finfo with fcinfo->flinfo, moving
MINARRAY_SIZE_FOR_HASHED_SAOP, caching typlen, etc. and the comment
updates). That would reduce the noise in the other patches and make them
somewhat easier to review.

> Performance
> -----------
> Release build, no LLVM, generic plan forced, warm cache, one Ryzen 7
> 4800H laptop.  Seq scan, "SELECT count(*) FROM t WHERE v = ANY($1)",
> 1,000,000 rows, median of 9:
> 
>     N       master      patched
>     6       59 ms       57 ms    (below threshold: linear both)
>     9       65 ms       50 ms
>    40      150 ms       52 ms
>   100      297 ms       52 ms
>  1000     2494 ms       51 ms

Nice!

Why does "patched" get faster with increasing N (57 ms for N=6 and 51 ms
for N=51)? It needs to create a much bigger hash map for N=51 than for
N=6. That shouldn't take very long but if anything, it shouldn't make
the query run faster.

> Patched is flat in N once hashed.  "IN ($1,...,$N)": 3.6x at N=9, 12x at
> N=60.  No change on paths that stay linear (N < 9, literal IN, pgbench).

That means the speedup is even greater for the IN($1, ..., $N) case
because in that case for every parameter extra work is spent non-hashed
variant? Do you have a table like the above for that variant?

> Single evaluation -- the PG 14 concern.  Plan built and run once, fresh
> connection:
> 
>   rows   N     master      patched
>      1   40    0.025 ms    0.028 ms
>      1  200    0.023 ms    0.035 ms   (+12 us, worst seen)
>   1000  100    0.316 ms    0.085 ms
> 
> Break-even is around 10 rows; worst case is +12 us to build a 200-entry
> hash for a one-row scan.

That seems reasonable and should be the same for the const case that
works today already. Maybe you can collect numbers for that case as well
and show that the maximum slowdown is not bigger than what we accepted
previously.

> Open question
> ------------
> cost_qual_eval charges the hashed cost for an opaque stable array using
> estimate_array_length()'s default guess, which slightly over-estimates
> startup for an array that turns out short at run time.  I have left that
> for a follow-up; happy to fold in a fix if reviewers prefer.
What are your ideas for improving on that? You cannot know the runtime
array length at planning time.

--
David Geier



Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
best xmg <bestxmg@gmail.com>
Дата:
Вложения:
Hi David,

Thanks for the comprehensive review.  It was very informative.

Attached is v2, split as you suggested (details below).

Please note that v2 was generated with Claude Code, so please don't
commit it yet.  I'm busy preparing for my exams, and I will finish
reviewing it line by line within two weeks.  In the meantime, I have
had an AI model check it many times to keep the number of bugs as low
as possible.

v2 also fixes these bugs in v1, each with a regression test now:

- In a PL/pgSQL simple expression, NOT IN / <> ALL compared with "="
  instead of "<>": v1 searched linearly there but kept the operator
  that hashed NOT IN uses.
- Some arrays that change from row to row were hashed once: arrays
  containing merge_action(), a set-returning function, or RETURNING
  OLD/NEW of a view column.  0002 now accepts only node types known to
  be fixed (an allowlist), so any other node is never hashed.
- A NULL scalar with an empty array returned NULL instead of false
  (true for NOT IN).
- In a JSON DEFAULT ... ON ERROR expression, an error in the array was
  not handled softly.  0002 doesn't hash there.

I also ran the whole test suite with a debug build that checks every
hashed result against a linear search, and compared about 60,000
random query executions with master.  Neither found anything else.

> That's indeed a pretty severe limitation that would be great to remove:
> Today, anything that doesn't use the database in the most
> straightforward doesn't profit from hashed IN.

Let me first make the scope precise, because my first mail described it
badly.

A prepared statement can run with two kinds of plan.  A custom plan is
built for each execution with the actual parameter values, so
"col = ANY ($1)" becomes "col = ANY ('{...}')", a Const, which the
existing PG 14 code hashes.  A generic plan is built once without values
and then reused, so the array stays a Param, which master searches
linearly for every row.  The generic plan saves planning time on every
execution, while a custom plan can be better because it sees the
values.

So the problem is specific to generic plans, plus arrays the planner can
never fold, such as the result of a stable function.  The table shows
whether the array is hashed (hash) or searched linearly (scan), with
12 elements unless noted.  "cust." is a custom plan, "gen." a generic
plan:

  master        patched
  cust.  gen.   cust.  gen.    query form

  Literal lists
  hash   hash   hash   hash    v IN (1, ..., 12)
  scan   scan   scan   scan    v IN (1, ..., 8)

  Parameters
  hash   scan   hash   hash    v = ANY ($1)
  hash   scan   hash   hash    v IN ($1, ..., $12)
  hash   scan   hash   hash    v IN ($1, 2, ..., 12)
  hash   scan   hash   hash    v = ANY ($1::int[])
  hash   scan   hash   hash    v = ANY (string_to_array($1, ','))
  scan   scan   scan   scan    v IN ($1, ..., $8)
  scan   scan   scan   scan    v = ANY ($1), only 5 elements
  hash   scan   hash   hash    SELECT v = ANY ($1) FROM t

  Stable and volatile functions
  scan   scan   hash   hash    v = ANY (stable_fn($1))
  scan   scan   hash   hash    v = ANY (current_setting('x')::int[])
  scan   scan   scan   scan    v = ANY (volatile_fn($1))

  NOT IN and other operators
  hash   scan   hash   hash    v NOT IN ($1, ..., $12)
  hash   scan   hash   hash    v <> ALL ($1)
  scan   scan   scan   scan    v < ANY ($1)  (no hash function)

  Arrays that change per row or group
  scan   scan   scan   scan    v = ANY (arr)  (arr is a column)
  scan   scan   scan   scan    v = ANY (ARRAY[v, v + 1, ...])
  scan   scan   scan   scan    HAVING 5 = ANY (array_agg(v))
  scan   scan   scan   scan    v = ANY (array_agg(v) OVER (...))
  scan   scan   scan   scan    v = ANY (ARRAY(SELECT ...))
  scan   scan   scan   scan    LATERAL: t.v = ANY (a.arr)

This matters in practice.  pgJDBC (after prepareThreshold), pgx,
asyncpg, psycopg 3 and PL/pgSQL all reuse prepared statements, and by
default PostgreSQL switches to the generic plan at the 6th execution if
it looks cheaper.  With a long list it often does, because the planner
assumes a $1 array has 10 elements.  For example, a 1M-row table
filtered by a 1000-element list and joined to a second table (release
build, default settings, medians of 5 runs):

  master:       custom plan 33 ms, generic plan 972 ms
  patched (v2): custom plan 31 ms, generic plan  30 ms

I also tried fixing this in choose_custom_plan(), by preferring a
custom plan when the generic plan would search a long parameter array.
That helps only in auto mode, not with force_generic_plan or for stable
expressions, and it re-plans every execution, so I think the executor
fix is better.

> one-off custom plan folds it to a Const and is fine -- which is
> why the slowdown tends to appear only after a statement has run a few
> times.  The PG 14 thread named the non-Const case as future work,
> deferred "from fear that we may slow down cases where the expression is
> evaluated only once".
>
> Why would that be? This "problem" also exists for the const case,
> doesn't it?

You're right, and my quote was misleading: building the hash table
for a single evaluation costs about the same for Const and non-Const
arrays (the measurements below show this).  In fact, the original
thread wanted this: Heikki suggested applying the optimization to
non-Const expressions and wrote "it would be nice to handle queries
like "WHERE column = ANY ($1)"" [1].

> We could make the choice of using the hashed SAOP or not depend on the
> estimated number of rows. But given that we don't do anything like that
> for the const case, I'm thinking we should do the same for the non-const
> case.

Agreed, I'll keep it consistent with the Const case.

> The patch is relatively big. How about splitting out the refactorings
> (replacing finfo with fcinfo->flinfo, moving
> MINARRAY_SIZE_FOR_HASHED_SAOP, caching typlen, etc. and the comment
> updates).

Done in v2:

- 0001 only refactors, with no behaviour change: finfo is replaced by
  fcinfo->flinfo, MIN_ARRAY_SIZE_FOR_HASHED_SAOP moves to primnodes.h,
  and the code that builds the hash table moves unchanged into a new
  function, saop_build_hashtable(), so that 0002 calls it instead of
  re-indenting it.
- 0002 is the feature and its tests.

Caching typlen stayed in 0002, because only the new short-array linear
path reads it; in 0001 it would be dead code.  I also dropped comment
rewording from v1 that the feature didn't need.

> Why does "patched" get faster with increasing N (57 ms for N=6 and 51 ms
> for N=51)?

The N=6 row is below MIN_ARRAY_SIZE_FOR_HASHED_SAOP (9), so it is a
linear search in both builds.  From N=9 on, patched uses the hash table
and stays flat; the 50-52 ms differences are noise.  Building the hash
table itself is cheap: about 0.6 us for 51 elements, the largest list
in your table, and 10 us for 1000, far too little to explain
differences of milliseconds.

> Do you have a table like the above for that variant?

Yes.  "SELECT count(*) FROM t WHERE v IN ($1, ..., $N)" on a 1M-row
table, generic plan, no parallel workers, each value matching one row
(release build, medians of 7 runs):

  N = 6:     master 154 ms,  patched 155 ms
  N = 9:     master 190 ms,  patched 52 ms
  N = 16:    master 250 ms,  patched 49 ms
  N = 64:    master 632 ms,  patched 50 ms
  N = 256:   master 2078 ms, patched 51 ms
  N = 1000:  master 7734 ms, patched 50 ms

> Maybe you can collect numbers for that case as well and show that the
> maximum slowdown is not bigger than what we accepted previously.

Here is the cost of a statement that uses the array only once, in
microseconds (generic plan, medians of 3 runs), with x the first
element of the array, the best case for a linear search:

- "literal": x = ANY ('{...}') on master, which master already hashes,
  so this is the cost accepted in PG 14
- "$1 linear": x = ANY ($1) on master, not hashed
- "$1 hashed": x = ANY ($1) with the patch

  N = 9:      literal 2.8,    $1 linear 2.8,  $1 hashed 3.0
  N = 100:    literal 5.1,    $1 linear 2.8,  $1 hashed 4.8
  N = 1000:   literal 12.9,   $1 linear 3.0,  $1 hashed 14.0
  N = 10000:  literal 159.2,  $1 linear 5.1,  $1 hashed 171.3

"$1 hashed" costs a little more than "literal": unlike a Const array,
a $1 array is not stored in the plan, so the patch copies it once
before building the hash table.  The worst case is therefore only
slightly above the one accepted for Const arrays in PG 14.

> What are your ideas for improving on that? You cannot know the runtime
> array length at planning time.

Agreed, not in general.  For IN ($1, ..., $N) the length is already
known at plan time, because it is an ArrayExpr, so only a bare Param or
a function result falls back to estimate_array_length()'s default of 10.
I propose to leave the costing as it is and document that, unless you
see a better option.

Just a kind reminder: I haven't reviewed v2 line by line myself yet.
Feedback and suggestions are very welcome, and I will respond to them,
together with v3, in about two weeks, after my exams.

[1] https://www.postgresql.org/message-id/557e8853-7cb8-9c01-6193-1d4109345401%40iki.fi

Regards,
Linden

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
best xmg <bestxmg@gmail.com>
Дата:
Вложения:
Hi David,

Attached is v3. I have reviewed every line of it myself, changed it
where needed, and tested it. Please review v3 instead of v2.

My answers to your questions in my last mail are still valid. The
performance numbers there are also still valid.

0001 only refactors, with no behavior change. 0002 is the feature and
its tests. Both apply cleanly to today's master.

Some code in 0002 may be hard to understand, because it handles rare
cases. For your reference, here is a brief explanation. I hope it
makes your review easier. Line numbers are in the v3-0002 patch file.

1. Line 113, use_hashed_step in ExecInitExprRec(): the hashed step
reads a non-Const array only once. That is wrong in a PL/pgSQL
simple expression, which is reused with new parameter values, and
in JSON ON ERROR or ON EMPTY, where errors must be caught. So these
cases use the plain step.

2. Line 129, negfuncid in ExecInitExprRec(): a hashed NOT IN looks
values up with "=" (negfuncid). The plain step must use the
operator itself, "<>".

3. Line 379, ExecEvalHashedScalarArrayOp(): on master, this step only
gets a Const array that the planner has checked: not NULL, and with
at least 9 elements. A non-Const array is only known at run time,
so it can be NULL, empty or short. These lines handle that the
same way as ExecEvalScalarArrayOp(), in the same order, so
NULL = ANY ('{}') still gives false.

4. Line 578, saop_array_may_vary_walker(): only arrays built from
Consts, external Params and the node types listed in the switch are
hashed. Anything else is rejected, including rare nodes that change
from row to row: merge_action(), OLD/NEW in RETURNING, and
set-returning functions. Vars of any level are rejected too,
because outer references are not yet Params here.

The full test suite passes, for 0001 alone and for both patches. I
also compared about 48,000 random queries with unpatched master, and
found no differences.

Any comments are very welcome.

Regards,
Linden

On Sun, Oct 11, 2026 11:36 AM, best xmg  wrote:
>>
>> Hi David,
>>
>> Thanks for the comprehensive review.  It was very informative.
>>
>> Attached is v2, split as you suggested (details below).
>>
>> Please note that v2 was generated with Claude Code, so please don't
>> commit it yet.  I'm busy preparing for my exams, and I will finish
>> reviewing it line by line within two weeks.  In the meantime, I have
>> had an AI model check it many times to keep the number of bugs as low
>> as possible.
>>
>> v2 also fixes these bugs in v1, each with a regression test now:
>>
>> - In a PL/pgSQL simple expression, NOT IN / <> ALL compared with "="
>>   instead of "<>": v1 searched linearly there but kept the operator
>>   that hashed NOT IN uses.
>> - Some arrays that change from row to row were hashed once: arrays
>>   containing merge_action(), a set-returning function, or RETURNING
>>   OLD/NEW of a view column.  0002 now accepts only node types known to
>>   be fixed (an allowlist), so any other node is never hashed.
>> - A NULL scalar with an empty array returned NULL instead of false
>>   (true for NOT IN).
>> - In a JSON DEFAULT ... ON ERROR expression, an error in the array was
>>   not handled softly.  0002 doesn't hash there.
>>
>> I also ran the whole test suite with a debug build that checks every
>> hashed result against a linear search, and compared about 60,000
>> random query executions with master.  Neither found anything else.
>>
>> > That's indeed a pretty severe limitation that would be great to remove:
>> > Today, anything that doesn't use the database in the most
>> > straightforward doesn't profit from hashed IN.
>>
>> Let me first make the scope precise, because my first mail described it
>> badly.
>>
>> A prepared statement can run with two kinds of plan.  A custom plan is
>> built for each execution with the actual parameter values, so
>> "col = ANY ($1)" becomes "col = ANY ('{...}')", a Const, which the
>> existing PG 14 code hashes.  A generic plan is built once without values
>> and then reused, so the array stays a Param, which master searches
>> linearly for every row.  The generic plan saves planning time on every
>> execution, while a custom plan can be better because it sees the
>> values.
>>
>> So the problem is specific to generic plans, plus arrays the planner can
>> never fold, such as the result of a stable function.  The table shows
>> whether the array is hashed (hash) or searched linearly (scan), with
>> 12 elements unless noted.  "cust." is a custom plan, "gen." a generic
>> plan:
>>
>>   master        patched
>>   cust.  gen.   cust.  gen.    query form
>>
>>   Literal lists
>>   hash   hash   hash   hash    v IN (1, ..., 12)
>>   scan   scan   scan   scan    v IN (1, ..., 8)
>>
>>   Parameters
>>   hash   scan   hash   hash    v = ANY ($1)
>>   hash   scan   hash   hash    v IN ($1, ..., $12)
>>   hash   scan   hash   hash    v IN ($1, 2, ..., 12)
>>   hash   scan   hash   hash    v = ANY ($1::int[])
>>   hash   scan   hash   hash    v = ANY (string_to_array($1, ','))
>>   scan   scan   scan   scan    v IN ($1, ..., $8)
>>   scan   scan   scan   scan    v = ANY ($1), only 5 elements
>>   hash   scan   hash   hash    SELECT v = ANY ($1) FROM t
>>
>>   Stable and volatile functions
>>   scan   scan   hash   hash    v = ANY (stable_fn($1))
>>   scan   scan   hash   hash    v = ANY (current_setting('x')::int[])
>>   scan   scan   scan   scan    v = ANY (volatile_fn($1))
>>
>>   NOT IN and other operators
>>   hash   scan   hash   hash    v NOT IN ($1, ..., $12)
>>   hash   scan   hash   hash    v <> ALL ($1)
>>   scan   scan   scan   scan    v < ANY ($1)  (no hash function)
>>
>>   Arrays that change per row or group
>>   scan   scan   scan   scan    v = ANY (arr)  (arr is a column)
>>   scan   scan   scan   scan    v = ANY (ARRAY[v, v + 1, ...])
>>   scan   scan   scan   scan    HAVING 5 = ANY (array_agg(v))
>>   scan   scan   scan   scan    v = ANY (array_agg(v) OVER (...))
>>   scan   scan   scan   scan    v = ANY (ARRAY(SELECT ...))
>>   scan   scan   scan   scan    LATERAL: t.v = ANY (a.arr)
>>
>> This matters in practice.  pgJDBC (after prepareThreshold), pgx,
>> asyncpg, psycopg 3 and PL/pgSQL all reuse prepared statements, and by
>> default PostgreSQL switches to the generic plan at the 6th execution if
>> it looks cheaper.  With a long list it often does, because the planner
>> assumes a $1 array has 10 elements.  For example, a 1M-row table
>> filtered by a 1000-element list and joined to a second table (release
>> build, default settings, medians of 5 runs):
>>
>>   master:       custom plan 33 ms, generic plan 972 ms
>>   patched (v2): custom plan 31 ms, generic plan  30 ms
>>
>> I also tried fixing this in choose_custom_plan(), by preferring a
>> custom plan when the generic plan would search a long parameter array.
>> That helps only in auto mode, not with force_generic_plan or for stable
>> expressions, and it re-plans every execution, so I think the executor
>> fix is better.
>>
>> > one-off custom plan folds it to a Const and is fine -- which is
>> > why the slowdown tends to appear only after a statement has run a few
>> > times.  The PG 14 thread named the non-Const case as future work,
>> > deferred "from fear that we may slow down cases where the expression is
>> > evaluated only once".
>> >
>> > Why would that be? This "problem" also exists for the const case,
>> > doesn't it?
>>
>> You're right, and my quote was misleading: building the hash table
>> for a single evaluation costs about the same for Const and non-Const
>> arrays (the measurements below show this).  In fact, the original
>> thread wanted this: Heikki suggested applying the optimization to
>> non-Const expressions and wrote "it would be nice to handle queries
>> like "WHERE column = ANY ($1)"" [1].
>>
>> > We could make the choice of using the hashed SAOP or not depend on the
>> > estimated number of rows. But given that we don't do anything like that
>> > for the const case, I'm thinking we should do the same for the non-const
>> > case.
>>
>> Agreed, I'll keep it consistent with the Const case.
>>
>> > The patch is relatively big. How about splitting out the refactorings
>> > (replacing finfo with fcinfo->flinfo, moving
>> > MINARRAY_SIZE_FOR_HASHED_SAOP, caching typlen, etc. and the comment
>> > updates).
>>
>> Done in v2:
>>
>> - 0001 only refactors, with no behaviour change: finfo is replaced by
>>   fcinfo->flinfo, MIN_ARRAY_SIZE_FOR_HASHED_SAOP moves to primnodes.h,
>>   and the code that builds the hash table moves unchanged into a new
>>   function, saop_build_hashtable(), so that 0002 calls it instead of
>>   re-indenting it.
>> - 0002 is the feature and its tests.
>>
>> Caching typlen stayed in 0002, because only the new short-array linear
>> path reads it; in 0001 it would be dead code.  I also dropped comment
>> rewording from v1 that the feature didn't need.
>>
>> > Why does "patched" get faster with increasing N (57 ms for N=6 and 51 ms
>> > for N=51)?
>>
>> The N=6 row is below MIN_ARRAY_SIZE_FOR_HASHED_SAOP (9), so it is a
>> linear search in both builds.  From N=9 on, patched uses the hash table
>> and stays flat; the 50-52 ms differences are noise.  Building the hash
>> table itself is cheap: about 0.6 us for 51 elements, the largest list
>> in your table, and 10 us for 1000, far too little to explain
>> differences of milliseconds.
>>
>> > Do you have a table like the above for that variant?
>>
>> Yes.  "SELECT count(*) FROM t WHERE v IN ($1, ..., $N)" on a 1M-row
>> table, generic plan, no parallel workers, each value matching one row
>> (release build, medians of 7 runs):
>>
>>   N = 6:     master 154 ms,  patched 155 ms
>>   N = 9:     master 190 ms,  patched 52 ms
>>   N = 16:    master 250 ms,  patched 49 ms
>>   N = 64:    master 632 ms,  patched 50 ms
>>   N = 256:   master 2078 ms, patched 51 ms
>>   N = 1000:  master 7734 ms, patched 50 ms
>>
>> > Maybe you can collect numbers for that case as well and show that the
>> > maximum slowdown is not bigger than what we accepted previously.
>>
>> Here is the cost of a statement that uses the array only once, in
>> microseconds (generic plan, medians of 3 runs), with x the first
>> element of the array, the best case for a linear search:
>>
>> - "literal": x = ANY ('{...}') on master, which master already hashes,
>>   so this is the cost accepted in PG 14
>> - "$1 linear": x = ANY ($1) on master, not hashed
>> - "$1 hashed": x = ANY ($1) with the patch
>>
>>   N = 9:      literal 2.8,    $1 linear 2.8,  $1 hashed 3.0
>>   N = 100:    literal 5.1,    $1 linear 2.8,  $1 hashed 4.8
>>   N = 1000:   literal 12.9,   $1 linear 3.0,  $1 hashed 14.0
>>   N = 10000:  literal 159.2,  $1 linear 5.1,  $1 hashed 171.3
>>
>> "$1 hashed" costs a little more than "literal": unlike a Const array,
>> a $1 array is not stored in the plan, so the patch copies it once
>> before building the hash table.  The worst case is therefore only
>> slightly above the one accepted for Const arrays in PG 14.
>>
>> > What are your ideas for improving on that? You cannot know the runtime
>> > array length at planning time.
>>
>> Agreed, not in general.  For IN ($1, ..., $N) the length is already
>> known at plan time, because it is an ArrayExpr, so only a bare Param or
>> a function result falls back to estimate_array_length()'s default of 10.
>> I propose to leave the costing as it is and document that, unless you
>> see a better option.
>>
>> Just a kind reminder: I haven't reviewed v2 line by line myself yet.
>> Feedback and suggestions are very welcome, and I will respond to them,
>> together with v3, in about two weeks, after my exams.
>>
>> [1] https://www.postgresql.org/message-id/557e8853-7cb8-9c01-6193-1d4109345401%40iki.fi
>>
>> Regards,
>> Linden

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
David Geier <geidav.pg@gmail.com>
Дата:
> Attached is v3. I have reviewed every line of it myself, changed it
> where needed, and tested it. Please review v3 instead of v2.
> 
> My answers to your questions in my last mail are still valid. The
> performance numbers there are also still valid.
> 
> 0001 only refactors, with no behavior change. 0002 is the feature and
> its tests. Both apply cleanly to today's master.

Thanks. That helped reviewing 0002.

> Some code in 0002 may be hard to understand, because it handles rare
> cases. For your reference, here is a brief explanation. I hope it
> makes your review easier. Line numbers are in the v3-0002 patch file.
> 
> 1. Line 113, use_hashed_step in ExecInitExprRec(): the hashed step
> reads a non-Const array only once. That is wrong in a PL/pgSQL
> simple expression, which is reused with new parameter values, and
> in JSON ON ERROR or ON EMPTY, where errors must be caught. So these
> cases use the plain step.
> 
> 2. Line 129, negfuncid in ExecInitExprRec(): a hashed NOT IN looks
> values up with "=" (negfuncid). The plain step must use the
> operator itself, "<>".
> 
> 3. Line 379, ExecEvalHashedScalarArrayOp(): on master, this step only
> gets a Const array that the planner has checked: not NULL, and with
> at least 9 elements. A non-Const array is only known at run time,
> so it can be NULL, empty or short. These lines handle that the
> same way as ExecEvalScalarArrayOp(), in the same order, so
> NULL = ANY ('{}') still gives false.
> 
> 4. Line 578, saop_array_may_vary_walker(): only arrays built from
> Consts, external Params and the node types listed in the switch are
> hashed. Anything else is rejected, including rare nodes that change
> from row to row: merge_action(), OLD/NEW in RETURNING, and
> set-returning functions. Vars of any level are rejected too,
> because outer references are not yet Params here.

Thanks for the explanations. They were useful. All of them should be
turned into comments in the code.

A comment saying why we cannot unify the Const and non-Const case in
execExprInterp.c would be useful. One could think that it might be a
good idea to now always go the non-Const route for code simplicity /
consistency.

Doesn't saop_array_may_vary_walker() misses T_CaseWhen? T_CaseExpr's
args is a list of CaseWhen nodes. When recursing it doesn't match
against T_CaseWhen and returns true while CaseWhen doesn't vary. I think
that would only occur in this form:

x = ANY(CASE WHEN $2 THEN $1 ELSE '{...}' END

And two nit comments:

- Use castNode() instead of C casts
- Use a wrapper around saop_array_may_vary_walker(), e.g.
saop_array_may_vary()

Beyond that, I would make the commit message less technical. This level
of detail should be code comments. The commit message should high-level
outline the change and its limitations. You could put there e.g. where
the optimization doesn't apply today and where it still doesn't apply
wit the commit's changes (soft errors, standalone expressions).

The rest LGTM.

--
David Geier


Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
best xmg <bestxmg@gmail.com>
Дата:
Вложения:
Hi David,

Thanks for the review. Attached is v4.

> Thanks for the explanations. They were useful. All of them should be
> turned into comments in the code.

Done.

> A comment saying why we cannot unify the Const and non-Const case in
> execExprInterp.c would be useful. One could think that it might be a
> good idea to now always go the non-Const route for code simplicity /
> consistency.

Done, above saop_hash_eval_array(). The non-Const route copies the
array, and a Const array needs no copy, because it is part of the plan.

> Doesn't saop_array_may_vary_walker() misses T_CaseWhen? T_CaseExpr's
> args is a list of CaseWhen nodes. When recursing it doesn't match
> against T_CaseWhen and returns true while CaseWhen doesn't vary. I think
> that would only occur in this form:
>
> x = ANY(CASE WHEN $2 THEN $1 ELSE '{...}' END

This form is hashed. The walker never gets a CaseWhen node, so
T_CaseWhen is not needed. I went through expression_tree_walker() and
ran a test to confirm this.

> - Use castNode() instead of C casts

Done.

> - Use a wrapper around saop_array_may_vary_walker(), e.g.
> saop_array_may_vary()

Done.

> Beyond that, I would make the commit message less technical. This level
> of detail should be code comments. The commit message should high-level
> outline the change and its limitations. You could put there e.g. where
> the optimization doesn't apply today and where it still doesn't apply
> wit the commit's changes (soft errors, standalone expressions).

Done. The commit message of 0002 now gives a high-level outline, and
says where the optimization still does not apply.

Any further feedback or guidance would be much appreciated.

Regards,
Linden

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
David Geier <geidav.pg@gmail.com>
Дата:
>> A comment saying why we cannot unify the Const and non-Const case in
>> execExprInterp.c would be useful. One could think that it might be a
>> good idea to now always go the non-Const route for code simplicity /
>> consistency.
> 
> Done, above saop_hash_eval_array(). The non-Const route copies the
> array, and a Const array needs no copy, because it is part of the plan.

But we could copy it, couldn't we? I'm more looking for a reason like
performance. As in, if we unified the code, what would happen that we
don't want to happen? Because we would get rid of a bunch of if-else and
harder to understand code if also Const arrays went through array_expr.

>> Doesn't saop_array_may_vary_walker() misses T_CaseWhen? T_CaseExpr's
>> args is a list of CaseWhen nodes. When recursing it doesn't match
>> against T_CaseWhen and returns true while CaseWhen doesn't vary. I think
>> that would only occur in this form:
>>
>> x = ANY(CASE WHEN $2 THEN $1 ELSE '{...}' END
> 
> This form is hashed. The walker never gets a CaseWhen node, so
> T_CaseWhen is not needed. I went through expression_tree_walker() and
> ran a test to confirm this.

Ah, this is because raw_expression_tree_walker_impl() skips T_WhenExpr
and directly recurses into its contents. You could add the case with a
comment to be on the safe side, if the code ever gets changed.

>> Beyond that, I would make the commit message less technical. This level
>> of detail should be code comments. The commit message should high-level
>> outline the change and its limitations. You could put there e.g. where
>> the optimization doesn't apply today and where it still doesn't apply
>> wit the commit's changes (soft errors, standalone expressions).

I thought that part below from v1 would be good to preserve in the
commit message:

"Since PG 14 (50e17ad281) a ScalarArrayOpExpr with "useOr" can be
evaluated with a hash table instead of a linear scan of the array, but
only when the array argument is a Const.  In a generic plan, a
parameterised list -- "col = ANY($1)", "col IN ($1, $2, ..., $N)",
"col = ANY($1::int[])", "col = ANY(string_to_array($1, ','))" -- keeps
a Param / ArrayExpr / FuncExpr in the plan and falls back to the
O(rows * N) linear path; so does an array computed by a stable function,
in any plan.  That is the shape emitted by JDBC setArray, psycopg and
asyncpg, and by any driver that expands an IN list into bind
parameters, and a prepared statement switches to its generic plan after
five executions when that plan looks cheaper.  MySQL and MariaDB
binary-search their sorted in_vector for the same query and stay
sub-linear."

This gives all the detail around when it doesn't work today, which is
very useful. Incorporating this into the commit message of v4 would be good.

> Any further feedback or guidance would be much appreciated.
I think you can go ahead and open a commit fest entry.

-- 
David Geier



Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
Ayoub Kazar <ayoub.kazar@data-bene.io>
Дата:
Вложения:

Hello Linden, David,

On 29/10/2026 10:46, David Geier wrote:
A comment saying why we cannot unify the Const and non-Const case in
execExprInterp.c would be useful. One could think that it might be a
good idea to now always go the non-Const route for code simplicity /
consistency.
Done, above saop_hash_eval_array(). The non-Const route copies the
array, and a Const array needs no copy, because it is part of the plan.
But we could copy it, couldn't we? I'm more looking for a reason like
performance. As in, if we unified the code, what would happen that we
don't want to happen? Because we would get rid of a bunch of if-else and
harder to understand code if also Const arrays went through array_expr.
+1 to simplifying the code, but we should be careful about hot-path overhead. In master, Const arrays are pre-validated at plan time, so ExecEvalHashedScalarArrayOp runs without checking for NULL, empty, or short arrays on every tuple (aren't those for the whole execution? so why check every time?). In v4, having this in the inner loop for every row is not insignificant. 

Doesn't saop_array_may_vary_walker() misses T_CaseWhen? T_CaseExpr's
args is a list of CaseWhen nodes. When recursing it doesn't match
against T_CaseWhen and returns true while CaseWhen doesn't vary. I think
that would only occur in this form:

x = ANY(CASE WHEN $2 THEN $1 ELSE '{...}' END
This form is hashed. The walker never gets a CaseWhen node, so
T_CaseWhen is not needed. I went through expression_tree_walker() and
ran a test to confirm this.
Ah, this is because raw_expression_tree_walker_impl() skips T_WhenExpr
and directly recurses into its contents. You could add the case with a
comment to be on the safe side, if the code ever gets changed.
AI suggests also NamedArtExpr and CollateExpr, i think they are safe as well to allow. 


Other findings:
While it is true that val <> ALL(array) == NOT(val = ANY (array)) (in Logic), however for user defined types and operators that are not strict, comparing NULL with a value can return false for both = and <> ...
So this makes the equivalence in that case not always true. (Attached is a reprod of the bug)



>> Open question
>> ------------
>> cost_qual_eval charges the hashed cost for an opaque stable array using
>> estimate_array_length()'s default guess, which slightly over-estimates
>> startup for an array that turns out short at run time. I have left that
>> for a follow-up; happy to fold in a fix if reviewers prefer.
> What are your ideas for improving on that? You cannot know the runtime
> array length at planning time.
We should be cautious about charging an O(1) per-tuple cost during generic planning when the array length is unknown, given that the executor can unilaterally decide to abandon hashing and execute an O(N) linear scan instead.

Here's a case:

CREATE TABLE large_bench (id bigint, cat int, val text);
INSERT INTO large_bench SELECT g, (g / 100) % 11, repeat('x', 100) FROM generate_series(1, 5000000) g;
CREATE INDEX idx_large_bench_cat ON large_bench(cat);
ANALYZE large_bench;
PREPARE p_query(int[]) AS SELECT * FROM large_bench WHERE cat = ANY($1);
SET plan_cache_mode = force_generic_plan;
Optimizer Costs:
Master: Bitmap Index Scan (187,282) < Seq Scan (203,410)
Patched v4: Seq Scan (165,910) < Bitmap Index Scan (187,282) (because of the cheap cost per tuple)

test executing with ARRAY[1, 2]:
Cold Cache:
Patched Seq Scan: 1,519 ms (reads 168k buffer pages, filters 4.09M rows)
Unpatched Index Scan: 129 ms (reads 24k buffer pages)
Impact: 11.7x slowdown
Warm Cache (5-run average):
Patched Seq Scan: 233.8 ms (touches all 90,910 table blocks)
Unpatched Index Scan: 84.1 ms (touches only 22,730 blocks)
Impact: 2.8x slowdown and 4x more buffer I/O

I think costing both cases (array length known or unknown) as unhashed linear scans isn't a bad idea maybe, i admit i haven't thought a lot about it yet.Regards,
Ayoub

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
best xmg <bestxmg@gmail.com>
Дата:
Вложения:
Hi David, Ayoub,

Thanks for the reviews. Attached is v5. 0001 is unchanged. 0002 has
all the changes below.

David wrote:
> But we could copy it, couldn't we? I'm more looking for a reason like
> performance. As in, if we unified the code, what would happen that we
> don't want to happen? Because we would get rid of a bunch of if-else and
> harder to understand code if also Const arrays went through array_expr.

You are right. In v5 a Const array goes through array_expr too, and
saop_hash_eval_array() is gone. The array is evaluated once, in
per-query memory, and it is no longer copied.

Ayoub wrote:
> +1 to simplifying the code, but we should be careful about hot-path
> overhead. In master, Const arrays are pre-validated at plan time,
> so ExecEvalHashedScalarArrayOp runs without checking for NULL, empty, or
> short arrays on every tuple (aren't those for the whole execution? so
> why check every time?). In v4, having this in the inner loop for every
> row is not insignificant.

Agreed. In v5, a NULL, empty or short array is handled behind one
check per row: is there a hash table? The result for a NULL scalar
depends only on the array, so it is worked out once, on the first
row. So a row makes no more checks than on master.

Looking up a value in a Const list is now faster than on master. The
step that loaded the Const array on every row is gone. The hashed step
itself also runs fewer instructions per row (callgrind, 10 items): 113
instead of 122 for a match, and 118 instead of 124 for no match.

David wrote:
> Ah, this is because raw_expression_tree_walker_impl() skips T_WhenExpr
> and directly recurses into its contents. You could add the case with a
> comment to be on the safe side, if the code ever gets changed.

Done.

> I thought that part below from v1 would be good to preserve in the
> commit message:

Done, with small fixes. NOT IN is hashed too since PG 15
(29f45e299e7), so I dropped "with useOr". I added casts to the list
of nodes. I wrote "psycopg 3", because psycopg 2 puts the values into
the query text on the client. I dropped the MySQL/MariaDB sentence,
because their manuals describe the binary search only for lists of
constants.

> I think you can go ahead and open a commit fest entry.

It already exists:
https://www.google.com/url?q=https://commitfest.postgresql.org/patch/7285/&source=gmail&ust=1793649679948000&sa=E
Please add yourself as a reviewer there, if you like.

Ayoub wrote:
> AI suggests also NamedArtExpr and CollateExpr, i think they are safe as
> well to allow.

Added both. They change nothing today: eval_const_expressions() runs
before our walker. It puts named arguments in position and turns a
CollateExpr into a RelabelType, so these queries are already hashed.
The two cases are only there in case that changes.

> While it is true that val <> ALL(array) == NOT(val = ANY (array)) (in
> Logic), however for user defined types and operators that are not
> strict, comparing NULL with a value can return false for both = and <> ...
> So this makes the equivalence in that case not always true. (Attached is
> a reprod of the bug)

Thanks for the reproducer. The root cause is the operators in your
test: the <> is not a valid negator of the =. The documentation [1]
requires "(x A y) equals NOT (x B y) for all possible inputs x, y", but
for a NULL input both return false. So NOT IN does not work well with
them even on master. The same question gets different answers,
depending on the length of the list:

SELECT v <> ALL (ARRAY[1,2,3,4,5,6,7,8,9]::my_int[])
FROM (SELECT NULL::my_int AS v OFFSET 0) s; -- t (9 items)

SELECT v <> ALL (ARRAY[1,2]::my_int[])
FROM (SELECT NULL::my_int AS v OFFSET 0) s; -- f (2 items)

The reason: a list of 9 or more items is hashed. A hashed NOT IN looks
for an equal item, so it calls = and inverts the result (since PG 15,
29f45e299e7). A shorter list is searched linearly, and that calls <>.
The two ways agree only if <> is the negator of =.

v5 hashes $1 too, so the example in your test now gets the hashed
answer.

Master's code for a hashed NOT IN depends on <> being the negator of =.
So does the recent fix for non-strict operators [2]. So I chose not
to fix it for now.

[1] https://www.google.com/url?q=https://www.postgresql.org/docs/current/xoper-optimization.html%23XOPER-NEGATOR&source=gmail&ust=1793649679948000&sa=E
[2] https://www.google.com/url?q=https://postgr.es/m/A16187AE-2359-4265-9F5E-71D015EC2B2D@outlook.com&source=gmail&ust=1793649679948000&sa=E

> We should be cautious about charging an O(1) per-tuple cost during
> generic planning when the array length is unknown, given that the
> executor can unilaterally decide to abandon hashing and execute an O(N)
> linear scan instead.

Agreed, fixed. An array of unknown length, such as ANY($1), is now
costed as a linear search, as on master. So your large_bench case gets
the same plan and costs as on master. Only a Const or an ARRAY[...]
with at least 9 items is costed as hashed. The planner knows their
length, so they are hashed at run time. This replaces my earlier
proposal to David, to leave the costing as it was.

I tested the plan choice on a 1M-row table with master and v5, and
timed each scan type. ANY($1) gets the same plans as master.
IN ($1, ..., $N) with N = 1000 changed from an index scan to a bitmap
scan in three of 31 cases. Two got faster (1.5x and 2.9x). One got
2.5 ms slower, but with random_page_cost = 1.1 v5 picks the faster
plan. The plan cache now picks the generic plan for such IN lists more
often, and it was 2-40% faster.

I also tested v5 against master: the regression suites with generic
plans, forced parallel workers and JIT; a random comparison over 20
data types; Valgrind; and a build that checks every hashed result
against the linear search. No differences.

Any further advice or corrections would be much appreciated.

Regards,
Linden


On Sat, Oct 31, 2026 at 6:56 AM Ayoub Kazar  wrote:
>
> Hello Linden, David,
>
> On 29/10/2026 10:46, David Geier wrote:
>
> A comment saying why we cannot unify the Const and non-Const case in
> execExprInterp.c would be useful. One could think that it might be a
> good idea to now always go the non-Const route for code simplicity /
> consistency.
>
> Done, above saop_hash_eval_array(). The non-Const route copies the
> array, and a Const array needs no copy, because it is part of the plan.
>
> But we could copy it, couldn't we? I'm more looking for a reason like
> performance. As in, if we unified the code, what would happen that we
> don't want to happen? Because we would get rid of a bunch of if-else and
> harder to understand code if also Const arrays went through array_expr.
>
> +1 to simplifying the code, but we should be careful about hot-path overhead. In master, Const arrays are pre-validated at plan time, so ExecEvalHashedScalarArrayOp runs without checking for NULL, empty, or short arrays on every tuple (aren't those for the whole execution? so why check every time?). In v4, having this in the inner loop for every row is not insignificant.
>
> Doesn't saop_array_may_vary_walker() misses T_CaseWhen? T_CaseExpr's
> args is a list of CaseWhen nodes. When recursing it doesn't match
> against T_CaseWhen and returns true while CaseWhen doesn't vary. I think
> that would only occur in this form:
>
> x = ANY(CASE WHEN $2 THEN $1 ELSE '{...}' END
>
> This form is hashed. The walker never gets a CaseWhen node, so
> T_CaseWhen is not needed. I went through expression_tree_walker() and
> ran a test to confirm this.
>
> Ah, this is because raw_expression_tree_walker_impl() skips T_WhenExpr
> and directly recurses into its contents. You could add the case with a
> comment to be on the safe side, if the code ever gets changed.
>
> AI suggests also NamedArtExpr and CollateExpr, i think they are safe as well to allow.
>
>
> Other findings:
> While it is true that val <> ALL(array) == NOT(val = ANY (array)) (in Logic), however for user defined types and operators that are not strict, comparing NULL with a value can return false for both = and <> ...
> So this makes the equivalence in that case not always true. (Attached is a reprod of the bug)
>
>
>
> >> Open question
> >> ------------
> >> cost_qual_eval charges the hashed cost for an opaque stable array using
> >> estimate_array_length()'s default guess, which slightly over-estimates
> >> startup for an array that turns out short at run time. I have left that
> >> for a follow-up; happy to fold in a fix if reviewers prefer.
> > What are your ideas for improving on that? You cannot know the runtime
> > array length at planning time.
> We should be cautious about charging an O(1) per-tuple cost during generic planning when the array length is unknown, given that the executor can unilaterally decide to abandon hashing and execute an O(N) linear scan instead.
>
> Here's a case:
>
> CREATE TABLE large_bench (id bigint, cat int, val text);
> INSERT INTO large_bench SELECT g, (g / 100) % 11, repeat('x', 100) FROM generate_series(1, 5000000) g;
> CREATE INDEX idx_large_bench_cat ON large_bench(cat);
> ANALYZE large_bench;
> PREPARE p_query(int[]) AS SELECT * FROM large_bench WHERE cat = ANY($1);
> SET plan_cache_mode = force_generic_plan;
>
> Optimizer Costs:
> Master: Bitmap Index Scan (187,282) < Seq Scan (203,410)
> Patched v4: Seq Scan (165,910) < Bitmap Index Scan (187,282) (because of the cheap cost per tuple)
>
> test executing with ARRAY[1, 2]:
> Cold Cache:
> Patched Seq Scan: 1,519 ms (reads 168k buffer pages, filters 4.09M rows)
> Unpatched Index Scan: 129 ms (reads 24k buffer pages)
> Impact: 11.7x slowdown
> Warm Cache (5-run average):
> Patched Seq Scan: 233.8 ms (touches all 90,910 table blocks)
> Unpatched Index Scan: 84.1 ms (touches only 22,730 blocks)
> Impact: 2.8x slowdown and 4x more buffer I/O
>
> I think costing both cases (array length known or unknown) as unhashed linear scans isn't a bad idea maybe, i admit i haven't thought a lot about it yet.
>
> Regards,
> Ayoub

Re: Hash a ScalarArrayOpExpr whose array is fixed for one execution

От:
David Geier <geidav.pg@gmail.com>
Дата:
Hi Linden,

> Thanks again for your reviews. Could you let me know if anything
> else needs to be done for v5? If you think it is ready, would you
> mind marking it Ready for Committer?

Your latest patch (v5) LGTM.
I've also added myself as reviewer to the commitfest entry.

-- 
David Geier



FAQ