COALESCE patch

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

COALESCE patch

От:
prankware <esavelievcode@gmail.com>
Дата:
Вложения:
Hi everyone,

The planner ignores column statistics when an equality has a COALESCE
expression on one side. For a clause like COALESCE(a, b) = $1, or a join on
COALESCE(t1.a, t1.b) = COALESCE(t2.c, t2.d), there are no statistics on the
COALESCE node itself, so eqsel() and eqjoinsel() return the generic 0.005
estimate while the per-column stats for a, b, c and d sit unused. The only way
around this today is an expression index or extended statistics on that exact
expression, which doesn't scale across many different COALESCE clauses.
estimate_hash_bucket_stats() has the same gap: a COALESCE hash key gets a
default ndistinct and therefore a default bucket size. Since these expressions
are common in joins and filters over nullable or fallback columns, the default
estimate can be far enough off to flip the join order or join method.

The idea is to estimate straight from the existing per-column stats, with no
extra statistics object. COALESCE(arg_1, ..., arg_n) returns arg_i only when
arg_1 .. arg_{i-1} are all NULL, so the chance of reaching branch i is the
product of stanullfrac over the earlier branches. Selectivity of
COALESCE(l_1..l_M) = COALESCE(r_1..r_N) is then the sum over branch pairs of
P(reach l_i) * P(reach r_j) * sel(l_i = r_j), and each sel(l_i = r_j) is a
recursive call back into eqsel()/eqjoinsel(). A non-COALESCE side is treated as
a one-branch list, so scalar COALESCE(a, b) = const falls out of the same code,
and the same decomposition feeds estimate_hash_bucket_stats(). If any branch is
missing stats, the code bails and today's behavior is unchanged.

A minimal example:

    CREATE TABLE t (a int, b int);
    INSERT INTO t
      SELECT CASE WHEN i % 5 < 2 THEN NULL ELSE i END, i
      FROM generate_series(1, 1000) i;
    ANALYZE t;

    EXPLAIN SELECT * FROM t WHERE COALESCE(a, b) = 42;

After ANALYZE, a is NULL in 400 of the 1000 rows (stanullfrac 0.4, ndistinct
600) and b has no NULLs (stanullfrac 0, ndistinct 1000). COALESCE(a, b) is
unique, so exactly one row matches. Each branch is weighted by the probability
of reaching it, the product of stanullfrac over the branches before it:

    branch a:  reach 1.0,  sel(a = 42) = (1 - 0.4) / 600  = 0.001
    branch b:  reach 0.4,  sel(b = 42) = (1 - 0.0) / 1000 = 0.001

    selectivity = 1.0 * 0.001 + 0.4 * 0.001 = 0.0014  ->  ~1 row out of 1000

The patch lands on ~1 row, matching reality. The 0.005 default (5 rows) is not
derived from the table at all: it is the 1/DEFAULT_NUM_DISTINCT constant the
planner falls back to with no statistics on the expression, so it stays 5 rows
regardless of the null fraction or the ndistinct of a and b.

Feedback is welcome.

Regards,
Egor Savelev,
Tantor Labs LLC,
https://tantorlabs.com/

Re: COALESCE patch

От:
prankware <esavelievcode@gmail.com>
Дата:
Вложения:
Thanks for the review — the test cases were very helpful.
You're right that v1 didn't improve the coalesce(col, const) case. The
reason is that a comparison of two constants got the default 0.005
instead of its real result, and joins with a constant on both sides
were skipped entirely.
v2 (attached) fixes both, and these four examples now estimate close
to the actual row counts.

Regards,
Egor Savelev,
Tantor Labs LLC,
https://tantorlabs.com

пт, 10 июл. 2026 г. в 12:27, Laurenz Albe :
>
> On Tue, 2026-06-30 at 16:48 +0300, prankware wrote:
>
> > The planner ignores column statistics when an equality has a COALESCE
> > expression on one side. For a clause like COALESCE(a, b) = $1, or a join on
> > COALESCE(t1.a, t1.b) = COALESCE(t2.c, t2.d), there are no statistics on the
> > COALESCE node itself, so eqsel() and eqjoinsel() return the generic 0.005
> > estimate while the per-column stats for a, b, c and d sit unused. The only way
> > around this today is an expression index or extended statistics on that exact
> > expression, which doesn't scale across many different COALESCE clauses.
> > estimate_hash_bucket_stats() has the same gap: a COALESCE hash key gets a
> > default ndistinct and therefore a default bucket size. Since these expressions
> > are common in joins and filters over nullable or fallback columns, the default
> > estimate can be far enough off to flip the join order or join method.
> >
> > The idea is to estimate straight from the existing per-column stats, with no
> > extra statistics object. COALESCE(arg_1, ..., arg_n) returns arg_i only when
> > arg_1 .. arg_{i-1} are all NULL, so the chance of reaching branch i is the
> > product of stanullfrac over the earlier branches. Selectivity of
> > COALESCE(l_1..l_M) = COALESCE(r_1..r_N) is then the sum over branch pairs of
> > P(reach l_i) * P(reach r_j) * sel(l_i = r_j), and each sel(l_i = r_j) is a
> > recursive call back into eqsel()/eqjoinsel(). A non-COALESCE side is treated as
> > a one-branch list, so scalar COALESCE(a, b) = const falls out of the same code,
> > and the same decomposition feeds estimate_hash_bucket_stats(). If any branch is
> > missing stats, the code bails and today's behavior is unchanged.
> >
> > Feedback is welcome.
>
> I think the idea is good, and the performance cost is incurred only when
> coalesce() expressions are present.  I am a bit worried about the execution
> time for queries that join two tables over lengthy coalesce clauses, as the
> cost is O(n*m) because of the sum.  But I think that such queries are extremely
> rare, so I don't worry too much.
>
> I found that the estimates are good if I use expressions like
> "coalesce(col1, col2)" in my query, but the estimates are as bad as before
> with the common case of "coalesce(col, constant)":
>
> CREATE TABLE b (col1 integer);
>
> /* three quarters NULL, the rest evenly distributed */
> INSERT INTO b
>    SELECT CASE WHEN random() >= 0.75 THEN random() * 1000 + 1 END
>    FROM generate_series(1, 10000);
>
> VACUUM (ANALYZE) b;
>
> /* force a hash join regardless of the estimates */
> SET work_mem = '512MB';
> SET enable_mergejoin = off;
> SET enable_nestloop = off;
>
>
> EXPLAIN (ANALYZE, SUMMARY OFF, BUFFERS OFF)
> SELECT *
> FROM b AS b1
>    JOIN b AS b2 ON coalesce(b1.col1, 0) = coalesce(b2.col1, 0);
>
>  Hash Join  (... rows=500000 ...) (actual ... rows=55125006.00 ...)
>    Hash Cond: (COALESCE(b1.col1, 0) = COALESCE(b2.col1, 0))
>    ->  Seq Scan on b b1  (... rows=10000 ...) (actual ... rows=10000.00 ..)
>    ->  Hash  (... rows=10000 ...) (actual ... rows=10000.00 ...)
>          Buckets: 16384  Batches: 1  Memory Usage: 451kB
>          ->  Seq Scan on b b2  (... rows=10000 ...) (actual ... rows=10000.00 ...)
>
> EXPLAIN (ANALYZE, SUMMARY OFF, BUFFERS OFF)
> SELECT *
> FROM b AS b1
>    JOIN b AS b2 ON coalesce(b1.col1, 0) = coalesce(b2.col1, 1);
>
>  Hash Join  (... rows=500000 ...) (actual ... rows=16654.00 ...)
>    Hash Cond: (COALESCE(b1.col1, 0) = COALESCE(b2.col1, 1))
>    ->  Seq Scan on b b1  (... rows=10000 ...) (actual ... rows=10000.00 ...)
>    ->  Hash  (... rows=10000 ...) (actual ... rows=10000.00 ...)
>          Buckets: 16384  Batches: 1  Memory Usage: 451kB
>          ->  Seq Scan on b b2  (... rows=10000 ...) (actual ... rows=10000.00 ...)
>
>
> EXPLAIN (ANALYZE, SUMMARY OFF, BUFFERS OFF)
> SELECT * FROM b WHERE coalesce(col1, 0) = 0;
>
>  Seq Scan on b  (... rows=40 ...) (actual ... rows=7424.00 ...)
>    Filter: (COALESCE(col1, 0) = 0)
>    Rows Removed by Filter: 2576
>
> EXPLAIN (ANALYZE, SUMMARY OFF, BUFFERS OFF)
> SELECT * FROM b WHERE coalesce(col1, 1) = 0;
>
>  Seq Scan on b  (... rows=40 ...) (actual ... rows=0.00 ...)
>    Filter: (COALESCE(col1, 1) = 0)
>    Rows Removed by Filter: 10000
>
>
> I think that the patch would be much more useful if it could improve
> such estimates.
>
> Yours,
> Laurenz Albe

Re: COALESCE patch

От:
Laurenz Albe <laurenz.albe@cybertec.at>
Дата:
On Fri, 2026-07-10 at 15:54 +0300, prankware wrote:
> Thanks for the review — the test cases were very helpful.
> You're right that v1 didn't improve the coalesce(col, const) case. The
> reason is that a comparison of two constants got the default 0.005
> instead of its real result, and joins with a constant on both sides
> were skipped entirely.
> v2 (attached) fixes both, and these four examples now estimate close
> to the actual row counts.

This version works fine.

It passes the regression tests.  It adds none of its own, but I
can't think of a good way to have stable regression tests for
anything that depends on optimizer statistics.

My biggest criticism at this point is the readability of the
code.  The function comments are alright, but try_coalesce_eq()
is tricky and could do with some comments that explain what is
going on and what the invariants are.

- Why is there a special treatment of a CoalesceExpr that
  match_coalesce_join_side() rejected?

- Why is it fine to assign a "bool" to a floating point variable?
  (An explicit type cast might be a good idea too.)

There are more places that could do with some illumination.

Also, why do you explicitly check for CoalesceExpr with less than
two arguments in match_coalesce_join_side()?

Yours,
Laurenz Albe


Re: COALESCE patch

От:
prankware <esavelievcode@gmail.com>
Дата:
Вложения:
Thanks for the review.

v3 (attached) adds comments at the two spots you asked about, and
answers the rest below.

The special case for a rejected CoalesceExpr:
match_coalesce_join_side() returns false both when a side is not a
COALESCE and when it is a COALESCE we chose not to decompose. In the
second case we must not treat the whole COALESCE as a single branch,
so we stop and let the caller estimate the clause the usual way. I
added a comment that says this.

The bool assigned to a float: I reworked it so the boolean result of
the operator maps explicitly to a selectivity of 1.0 or 0.0, with a
comment.

The check for fewer than two arguments: you're right that it's
redundant — a single-argument COALESCE is handled correctly without
it, so I removed it.

Feedback is welcome.

Regards,
Egor Savelev,
Tantor Labs LLC,
https://tantorlabs.com

чт, 16 июл. 2026 г. в 17:13, Laurenz Albe :
>
> On Fri, 2026-07-10 at 15:54 +0300, prankware wrote:
> > Thanks for the review — the test cases were very helpful.
> > You're right that v1 didn't improve the coalesce(col, const) case. The
> > reason is that a comparison of two constants got the default 0.005
> > instead of its real result, and joins with a constant on both sides
> > were skipped entirely.
> > v2 (attached) fixes both, and these four examples now estimate close
> > to the actual row counts.
>
> This version works fine.
>
> It passes the regression tests.  It adds none of its own, but I
> can't think of a good way to have stable regression tests for
> anything that depends on optimizer statistics.
>
> My biggest criticism at this point is the readability of the
> code.  The function comments are alright, but try_coalesce_eq()
> is tricky and could do with some comments that explain what is
> going on and what the invariants are.
>
> - Why is there a special treatment of a CoalesceExpr that
>   match_coalesce_join_side() rejected?
>
> - Why is it fine to assign a "bool" to a floating point variable?
>   (An explicit type cast might be a good idea too.)
>
> There are more places that could do with some illumination.
>
> Also, why do you explicitly check for CoalesceExpr with less than
> two arguments in match_coalesce_join_side()?
>
> Yours,
> Laurenz Albe

Re: COALESCE patch

От:
Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>
Дата:
While reviewing v6, I noticed try_coalesce_eq() in eqjoinsel() returns 
before the function ever looks at sjinfo->jointype, so SEMI/ANTI joins 
get the same formula meant for INNER/LEFT/FULL. I'm not sure it is true. 
Shouldn't the fat path be restricted to INNER/LEFT/FULL until SEMI/ANTI 
get their own existence-base treatment?

--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/



Re: COALESCE patch

От:
prankware <esavelievcode@gmail.com>
Дата:
Вложения:
Hi,
For SEMI/ANTI joins the selectivity is existence-based - whether an
outer row has at least one match - so it cannot be written as the
inner-join pair sum. It is estimated as follows.
First, for each side a single key distribution is built from the
COALESCE branches. Each branch is weighted by the probability of
reaching it (the product of the earlier branches' null fractions), so
the merged frequency of a value is:

F(value) = P(reach branch 1) * freq(value in branch 1)
         + P(reach branch 2) * freq(value in branch 2)
         + ...

Each side also carries its null fraction and distinct count.
Then the two keys are combined once:

sel = matchfreq + uncertainfrac * uncertain

matchfreq     - total frequency of outer MCV values that also appear
on the inner side;
uncertain     - the outer non-NULL mass the MCV does not cover, (1 -
outer_nullfrac) - seen;
uncertainfrac - the estimated match share of that tail,
clamp(inner_ndistinct / outer_ndistinct),
                or 0.5 when a distinct count is unknown.

Finally sel is capped at 1 - outer_nullfrac, since a semi-join keeps
at most the non-NULL outer rows. This is the SEMI selectivity; the
join-size code inverts it for ANTI.

Best regards,
Egor Savelev,
Tantor Labs


ср, 23 сент. 2026 г. в 07:35, Ilia Evdokimov :
>
> While reviewing v6, I noticed try_coalesce_eq() in eqjoinsel() returns
> before the function ever looks at sjinfo->jointype, so SEMI/ANTI joins
> get the same formula meant for INNER/LEFT/FULL. I'm not sure it is true.
> Shouldn't the fat path be restricted to INNER/LEFT/FULL until SEMI/ANTI
> get their own existence-base treatment?
>
> --
> Best regards,
> Ilia Evdokimov,
> Tantor Labs LLC,
> https://tantorlabs.com/
>

Re: COALESCE patch

От:
Ilia Evdokimov <ilidock95@gmail.com>
Дата:
On Mon, Oct 19, 2026 at 4:52 PM prankware  wrote:
>
> Hi,
> For SEMI/ANTI joins the selectivity is existence-based - whether an
> outer row has at least one match - so it cannot be written as the
> inner-join pair sum.

I found two cases where the current calculation gives incorrect estimates.

1. An outer MCV value that is absent from the inner MCV list may still
exist in the inner relation.
```
CREATE TABLE coalesce_outer AS
SELECT 7::int AS a
FROM generate_series(1, 10000);

CREATE TABLE coalesce_inner AS
SELECT g::int AS b
FROM generate_series(1, 10000) AS g;

ANALYZE coalesce_outer;
ANALYZE coalesce_inner;

EXPLAIN ANALYZE
SELECT *
FROM coalesce_outer o
WHERE EXISTS (
    SELECT 1
    FROM coalesce_inner i
    WHERE coalesce(o.a, -1) = i.b
);
                                                            QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------
 Hash Semi Join  (cost=289.00..479.25 rows=1 width=4) (actual
time=0.836..1.618 rows=10000.00 loops=1)
   Hash Cond: (COALESCE(o.a, '-1'::integer) = i.b)
   Buffers: shared hit=214 dirtied=2 written=8
   ->  Seq Scan on coalesce_outer o  (cost=0.00..164.00 rows=10000
width=4) (actual time=0.157..0.414 rows=10000.00 loops=1)
         Buffers: shared hit=107 dirtied=1 written=4
   ->  Hash  (cost=164.00..164.00 rows=10000 width=4) (actual
time=0.656..0.656 rows=10000.00 loops=1)
         Buckets: 16384  Batches: 1  Memory Usage: 480kB
         Buffers: shared hit=107 dirtied=1 written=4
         ->  Seq Scan on coalesce_inner i  (cost=0.00..164.00
rows=10000 width=4) (actual time=0.059..0.326 rows=10000.00 loops=1)
               Buffers: shared hit=107 dirtied=1 written=4
 Planning:
   Buffers: shared hit=71 read=7
 Planning Time: 0.206 ms
 Execution Time: 1.731 ms
(14 rows)
```

2. The inner distinct count doesn't account for restrictions on the inner input.
```
EXPLAIN ANALYZE
SELECT *
FROM coalesce_inner o
WHERE EXISTS (
    SELECT 1
    FROM coalesce_inner i
    WHERE i.b <= 10
      AND coalesce(o.b, -1) = i.b
);
                                                            QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------
 Hash Join  (cost=440.17..440.35 rows=10000 width=4) (actual
time=3.466..3.477 rows=10.00 loops=1)
   Hash Cond: (i.b = COALESCE(o.b, '-1'::integer))
   Buffers: shared hit=90
   ->  Unique  (cost=170.17..170.22 rows=10 width=4) (actual
time=0.815..0.820 rows=10.00 loops=1)
         Buffers: shared hit=45
         ->  Sort  (cost=170.17..170.19 rows=10 width=4) (actual
time=0.812..0.814 rows=10.00 loops=1)
               Sort Key: i.b
               Sort Method: quicksort  Memory: 25kB
               Buffers: shared hit=45
               ->  Seq Scan on coalesce_inner i  (cost=0.00..170.00
rows=10 width=4) (actual time=0.009..0.803 rows=10.00 loops=1)
                     Filter: (b <= 10)
                     Rows Removed by Filter: 9990
                     Buffers: shared hit=45
   ->  Hash  (cost=145.00..145.00 rows=10000 width=4) (actual
time=2.614..2.614 rows=10000.00 loops=1)
         Buckets: 16384  Batches: 1  Memory Usage: 480kB
         Buffers: shared hit=45
         ->  Seq Scan on coalesce_inner o  (cost=0.00..145.00
rows=10000 width=4) (actual time=0.019..0.804 rows=10000.00 loops=1)
               Buffers: shared hit=45
 Planning:
   Buffers: shared hit=13
 Planning Time: 0.490 ms
 Execution Time: 3.528 ms
(22 rows)

```

--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/


FAQ