Extended statistics improvement: multi-column MCV missing values

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

Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Hi,

Postgres only uses multi-column MCVs when the value we are looking for is in the list. If not, it falls back into individual independent statistics to estimate selectivity.
However, a miss in a multi-column MCV list still yields valuable information that it currently throws away: we know that the combination's frequency is strictly bounded by the frequency of the last (least common) item in that MCV list.

Test case
=========
```
-- 1. Create a minimal table
DROP TABLE IF EXISTS planner_trap;
CREATE TABLE planner_trap (
    col_a integer,
    col_b integer,
    col_c integer,
    sort_col integer
);

-- 2. 1 becomes the most common value (MCV) for all three columns.
INSERT INTO planner_trap (col_a, col_b, col_c, sort_col)
SELECT
    (pow(random(), 5) * 100)::integer + 1,
    (pow(random(), 5) * 10)::integer + 1,
    (pow(random(), 5) * 50)::integer + 1,
    i
FROM generate_series(1, 100000) AS i;

-- 3. Create indexes
CREATE INDEX idx_planner_trap_sort ON planner_trap(sort_col);
CREATE INDEX idx_planner_trap_a_b_c ON planner_trap(col_a, col_b, col_c);

-- 4. Make the exact combination (1, 1, 1) yield zero rows. This ensures it won't appear
-- in the MCV list, even though the value '1' remains the most common for each individual column.
UPDATE planner_trap
SET col_a = 2
WHERE col_a = 1 AND col_b = 1 AND col_c = 1;

-- 5. Create MCV statistics
CREATE STATISTICS (mcv) on col_a, col_b, col_c FROM planner_trap;
ANALYZE planner_trap;
```

The planner multiplies the individual selectivities and overestimates the row count (5909; actual=0):
```
postgres=# EXPLAIN ANALYZE SELECT * FROM planner_trap WHERE col_a = 1 AND col_b = 1 AND col_c = 1 ORDER BY sort_col DESC LIMIT 10;
                                                                          QUERY PLAN                                                                          
---------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.29..7.72 rows=10 width=16) (actual time=14.632..14.633 rows=0.00 loops=1)
   Buffers: shared hit=16355 dirtied=1
   ->  Index Scan Backward using idx_planner_trap_sort on planner_trap  (cost=0.29..4386.99 rows=5909 width=16) (actual time=14.630..14.630 rows=0.00 loops=1)
         Filter: ((col_a = 1) AND (col_b = 1) AND (col_c = 1))
         Rows Removed by Filter: 100000
         Index Searches: 1
         Buffers: shared hit=16355 dirtied=1
 Planning:
   Buffers: shared hit=33 read=1
 Planning Time: 0.478 ms
 Execution Time: 14.651 ms
```

1. Cap selectivity with the last MCV item's frequency
=====================================================
Applying the last MCV cap here, Postgres estimates 117 rows: 0.001167 * 100000 = 117
```
postgres=# SELECT m.* FROM pg_statistic_ext join pg_statistic_ext_data on (oid = stxoid),
                pg_mcv_list_items(stxdmcv) m WHERE stxname = 'planner_trap_col_a_col_b_col_c_stat' and index = 99;
 index |  values  |  nulls  |       frequency       | base_frequency
-------+----------+---------+-----------------------+----------------
    99 | {1,1,31} | {f,f,f} | 0.0011666666666666668 | 0.001049409536
```

making postgres to choose a better plan:
```
 Limit  (cost=300.72..300.75 rows=10 width=16) (actual time=0.045..0.046 rows=0.00 loops=1)
   Buffers: shared hit=3 read=2
   ->  Sort  (cost=300.72..301.02 rows=117 width=16) (actual time=0.043..0.044 rows=0.00 loops=1)
         Sort Key: sort_col DESC
         Sort Method: quicksort  Memory: 25kB
         Buffers: shared hit=3 read=2
         ->  Bitmap Heap Scan on planner_trap  (cost=5.78..298.19 rows=117 width=16) (actual time=0.026..0.027 rows=0.00 loops=1)
               Recheck Cond: ((col_a = 1) AND (col_b = 1) AND (col_c = 1))
               Buffers: shared read=2
               ->  Bitmap Index Scan on idx_planner_trap_a_b_c  (cost=0.00..5.76 rows=117 width=0) (actual time=0.019..0.020 rows=0.00 loops=1)
                     Index Cond: ((col_a = 1) AND (col_b = 1) AND (col_c = 1))
                     Index Searches: 1
                     Buffers: shared read=2
 Planning:
   Buffers: shared hit=51 read=8 dirtied=4
 Planning Time: 0.742 ms
 Execution Time: 0.094 ms
```

2. Estimate selectivity as Postgres does for single-column values not in MCVs
=============================================================================
While that significantly improves estimations, we could mirror what Postgres already does for individual MCVs. Quote from the official documentation:
> The approach is to use the fact that the value is not in the list, combined with the knowledge of the frequencies for all of the MCVs:
> That is, add up all the frequencies for the MCVs and subtract them from one, then divide by the number of other distinct values.

To achieve this, we need to store an ndistinct estimation alongside the MCVs that can be used for partial or entire column match.

P(1, 1, 1) = (1 - sum(MCVs)) / (ndistinct(col_a, col_b, col_c) - MCV_list_size)

```
postgres=# SELECT sum(m.frequency) FROM pg_statistic_ext join pg_statistic_ext_data on (oid = stxoid),
                pg_mcv_list_items(stxdmcv) m WHERE stxname = 'planner_trap_col_a_col_b_col_c_stat';
         sum        
---------------------
 0.39456666666666645
 
postgres=# SELECT stxkeys AS k, stxdndistinct AS nd
  FROM pg_statistic_ext join pg_statistic_ext_data on (oid = stxoid)
  WHERE stxname = 'stts2';
   k   |                      nd                                                                                      
-------+---------------------------------------------------
 1 2 3 | [...{"attributes": [1, 2, 3], "ndistinct": 8511}]
```

Then (1 - 0.39456666666666645) / (8511 - 100) = 0.000071981; 0.000071981 * 100000 = 7 rows
```
 Limit  (cost=30.30..30.32 rows=7 width=16) (actual time=0.035..0.036 rows=0.00 loops=1)
   Buffers: shared hit=2
   ->  Sort  (cost=30.30..30.32 rows=7 width=16) (actual time=0.033..0.034 rows=0.00 loops=1)
         Sort Key: sort_col DESC
         Sort Method: quicksort  Memory: 25kB
         Buffers: shared hit=2
         ->  Bitmap Heap Scan on planner_trap  (cost=4.38..30.20 rows=7 width=16) (actual time=0.028..0.029 rows=0.00 loops=1)
               Recheck Cond: ((col_a = 1) AND (col_b = 1) AND (col_c = 1))
               Buffers: shared hit=2
               ->  Bitmap Index Scan on idx_planner_trap_a_b_c  (cost=0.00..4.38 rows=7 width=0) (actual time=0.022..0.022 rows=0.00 loops=1)
                     Index Cond: ((col_a = 1) AND (col_b = 1) AND (col_c = 1))
                     Index Searches: 1
                     Buffers: shared hit=2
 Planning Time: 0.192 ms
 Execution Time: 0.057 ms
```

I think this is a cheap way to prevent bad estimations. The storage overhead of adding an ndistinct field is trivial compared to the MCV list itself, and the O(1) arithmetic during planning adds no measurable overhead. I look forward to your feedback before drafting a patch.

Best,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>
Дата:

Hi Enrique,

On 5/18/26 19:09, Enrique Sánchez wrote:


Postgres only uses multi-column MCVs when the value we are looking for is in the list. If not, it falls back into individual independent statistics to estimate selectivity.
However, a miss in a multi-column MCV list still yields valuable information that it currently throws away: we know that the combination's frequency is strictly bounded by the frequency of the last (least common) item in that MCV list.

LGTM. If the multicolumn MCV statistics exists and the clause combination is absent from the MCV-list, we can use the least frequent MCV item as an upper bound. BTW, this only applies to AND-clauses.



2. Estimate selectivity as Postgres does for single-column values not in MCVs
=============================================================================
While that significantly improves estimations, we could mirror what Postgres already does for individual MCVs. Quote from the official documentation:
> The approach is to use the fact that the value is not in the list, combined with the knowledge of the frequencies for all of the MCVs:
> That is, add up all the frequencies for the MCVs and subtract them from one, then divide by the number of other distinct values.

To achieve this, we need to store an ndistinct estimation alongside the MCVs that can be used for partial or entire column match.

P(1, 1, 1) = (1 - sum(MCVs)) / (ndistinct(col_a, col_b, col_c) - MCV_list_size)


...

I think this is a cheap way to prevent bad estimations. The storage overhead of adding an ndistinct field is trivial compared to the MCV list itself, and the O(1) arithmetic during planning adds no measurable overhead. I look forward to your feedback before drafting a patch.

For this, the ndistinct extended statistics already exist. If both MCV and ndistinct statistics are present on the same column set, the formula is correct. There are already places in the code that compute ndistinct for columns without extended ndistinct statistics (see estimate_num_groups) - but it is worth thinking carefully about whether the added complexity is justified before going down that path.

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

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi Ilia,

> 1. Cap selectivity with the last MCV item's frequency

I've attached a draft patch. It's split into 4 commits to make it easier to review. It adds the MCV cap for AND (equality, IN, ANY) clauses. Looking forward to your feedback.

On 5/19/26 0:13, Ilia Evdokimov wrote:
Postgres only uses multi-column MCVs when the value we are looking for is in the list. If not, it falls back into individual independent statistics to estimate selectivity.
However, a miss in a multi-column MCV list still yields valuable information that it currently throws away: we know that the combination's frequency is strictly bounded by the frequency of the last (least common) item in that MCV list.

LGTM. If the multicolumn MCV statistics exists and the clause combination is absent from the MCV-list, we can use the least frequent MCV item as an upper bound. BTW, this only applies to AND-clauses.

Given that the inclusion-exclusion principle (P(A OR B) = P(A) + P(B) - P(A AND B)) is used to calculate OR paths, we could use the same cap to improve the overlap estimation (P(A AND B)).

2. Estimate selectivity as Postgres does for single-column values not in MCVs
=============================================================================
While that significantly improves estimations, we could mirror what Postgres already does for individual MCVs. Quote from the official documentation:
> The approach is to use the fact that the value is not in the list, combined with the knowledge of the frequencies for all of the MCVs:
> That is, add up all the frequencies for the MCVs and subtract them from one, then divide by the number of other distinct values.

To achieve this, we need to store an ndistinct estimation alongside the MCVs that can be used for partial or entire column match.

P(1, 1, 1) = (1 - sum(MCVs)) / (ndistinct(col_a, col_b, col_c) - MCV_list_size)
...
I think this is a cheap way to prevent bad estimations. The storage overhead of adding an ndistinct field is trivial compared to the MCV list itself, and the O(1) arithmetic during planning adds no measurable overhead. I look forward to your feedback before drafting a patch.

For this, the ndistinct extended statistics already exist. If both MCV and ndistinct statistics are present on the same column set, the formula is correct. There are already places in the code that compute ndistinct for columns without extended ndistinct statistics (see estimate_num_groups) - but it is worth thinking carefully about whether the added complexity is justified before going down that path.

I think that the implementation would look similar to the attached patch. The only added complexity is getting the ndistinct estimation. There are 2 ways:
- Rely on the extended ndistinct statistic if it exists
- Calculate the ndistinct(col_a, col_b, col_c) statistic as part of the MCV. The storage cost is negligible compared to the MCV list and it keeps the MCV statistic complete, so it doesn't need to check if the ndistinct statistic exists. That would be a change on the MCV struct, meaning a change in the mcvlist->type.

I can start working on a proposal for this second part. Let me know what you think.

Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi, thank you for reviewing it.

Tue, 02 Jun 2026 at 0:18, Zsolt Parragi (<zsolt.parragi@percona.com>) wrote:
> The strongest
> case is a top-level AND condition with equality clauses for all columns

I see one issue related to that with the current patch, having the
same amount of conditions as the table doesn't mean that we have
conditions for all columns.
I've fixed this in the v2 patch attached above (also attached here for completeness). It focuses on the basic full-dimensional top-level AND equality miss
Now we construct a Bitmapset with the columns the clause covers and compare it to `stat->keys` that contains the columns covered by the MCV statistic.

Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi,

1. Full-dimensional top-level AND equality miss, using the
ndistinct-based average estimate when matching ndistinct statistics
exist, with the least-MCV frequency as an upper bound; otherwise
using the cap alone.

I've implemented the ndistinct-based estimation and attached it as v3-0002. The patch applies cleanly and pg-ci.yml passes.

## v3-0001
- logic remains the same
- added a `IsA(clause, RestrictInfo)` check before casting to RestrictInfo in `mcv_can_cap()`
- added some tests

## v3-0002
- used ndistinct to calculate `non_mcv_sel = (1.0 - mcv_totalsel) / (ndistinct - mcv_nitems)` and applied it as an upper bound for non-MCV combinations, similarly to what `var_eq_const()` does in `selfuncs.c`

Looking forward to your feedback!

Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>
Дата:

On 6/7/26 18:22, Enrique Sánchez wrote:

## v3-0001
- logic remains the same
- added a `IsA(clause, RestrictInfo)` check before casting to RestrictInfo in `mcv_can_cap()`
- added some tests

1. mcv_can_cap() reimplements logic already present in dependency_is_compatible_clause(). Shall we combine the two in order to avoid code duplication?

2. mcv_can_cap() runs unconditionally before the if (is_or) branch, but can_cap is only consumed in the else/AND branch. This means mcv_can_cap() - including get_oprrest, syscache lookups per clause - runs for every OR query as wasted work. Both can_cap and covered_attnums should be moved inside the else branch.



## v3-0002
- used ndistinct to calculate `non_mcv_sel = (1.0 - mcv_totalsel) / (ndistinct - mcv_nitems)` and applied it as an upper bound for non-MCV combinations, similarly to what `var_eq_const()` does in `selfuncs.c`

get_ndistinct_for_keys() reimplements the ndistinct item lookup already present in estimate_multivariate_ndistinct(). Both functions iterate over MVNDistinct->items match by attributes count.

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


Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi, thank you for the feedback!

On 9/7/2026 14:39, Ilia Evdokimov (<ilya.evdokimov@tantorlabs.com>) wrote:

1. mcv_can_cap() reimplements logic already present in dependency_is_compatible_clause(). Shall we combine the two in order to avoid code duplication?

It's true that some of the checks that are in `mcv_can_cap()` are already in `dependency_is_compatible_clause()`. They both return the same value when there's a pseudo-constant and the clause is `=`, `= TRUE` or `= FALSE`. Rest of the cases are different (IS NULL, ANY/IN, OR).

We would need to add surrounding logic because even for the matching cases, `mcv_can_cap()` doesn't need the pseudo-constant check that `dependency_is_compatible_clause()` requires for the `=` branch, among other checks.
We won't gain much from combining both: the number of removed lines is compensated with the added surrounding logic; and things will be more convoluted.

Moreover, the two functions will evolve independently because they serve different stats, so coupling them would create undesirable cross-dependency. I would prefer to maintain it as it is.

2. mcv_can_cap() runs unconditionally before the if (is_or) branch, but can_cap is only consumed in the else/AND branch. This means mcv_can_cap() - including get_oprrest, syscache lookups per clause - runs for every OR query as wasted work. Both can_cap and covered_attnums should be moved inside the else branch.

Makes sense. I've modified it, you can check v4-0001. It only made sense to have it there if we implement the OR path, which might be done in a future patch.

get_ndistinct_for_keys() reimplements the ndistinct item lookup already present in estimate_multivariate_ndistinct(). Both functions iterate over MVNDistinct->items match by attributes count.

Right! I've created a helper and used it in both places. You can check v4-0002.

I've checked that the patch applies cleanly and pg-ci.yml passes. 

Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>
Дата:

On 6/10/26 03:57, Enrique Sánchez wrote:

You can check v4-0002.

It's generally not safe to compare floating-point values for equality. I mean using `mcv_sel == 0.0` to detect that there are no extended MCV matches. IMO, we should use a bool variable (similar to how var_eq_const() does it) to track whether any MCV item matched, specifically in the loop where we check extended MCV matches in mcv_clauselist_selectivity(), and use that instead of checking `mcv_sel == 0.0`.

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

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi,

On 15/06/26 23:13, Ilia Evdokimov wrote:

It's generally not safe to compare floating-point values for equality. I mean using `mcv_sel == 0.0` to detect that there are no extended MCV matches. IMO, we should use a bool variable (similar to how var_eq_const() does it) to track whether any MCV item matched, specifically in the loop where we check extended MCV matches in mcv_clauselist_selectivity().

Makes sense, I've fixed it in v5-0002.

I've also created a commit fest entry for this patch: https://commitfest.postgresql.org/patch/6898/ 

Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi, I've rebased my patch as [1] got merged.


Best regards,
Enrique.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Вложения:
Hi Ilia, thanks for the review!

I've fixed the cosmetic nits in v7 and attached it to the next email.

Best regards,
Enrique.

On, 24 Jul 2026 at 17:03, Ilia Evdokimov (<ilya.evdokimov@tantorlabs.com>) wrote:
The overall approach looks architecturally correctly. Just two cosmetic
nits:

1. In `mcv_can_cap()`, the early-exit branch uses braces around `return
false`. This would normally be written without braces.

2. The doc comment above `mcv_can_cap()` says condition requires the
clause to be either an  equality operator, or a bare boolean Var, but
implementation actually handles one more cases - `NOT var`

3. Apply pgindent into diff.

Re: Extended statistics improvement: multi-column MCV missing values

От:
Enrique Sánchez <enriqueesanchz@gmail.com>
Дата:
Hi all,

Following up on my previous mail: after looking further into 0002, I'd
like to limit this patch to 0001 and leave the ndistinct part out.

The reasons:

- 0001 is a real bound, 0002 is not. Every combination missing from the
  MCV list is at most as frequent as the least common tracked item, so
  capping there cannot make an estimate worse, and improves the cases
  where the per-column estimate is above that frequency.

- 0001 is self-contained. It fixes the case that started this thread
  (individually common values whose combination is missing from the
  MCV list).

- 0002 is an estimate, not a bound, and it only helps when the columns
  are dependent. When they are close to independent, the current
  per-column estimate is already accurate.

v7, attached to my previous mail, addresses the comments. I'll leave
v7-0001 as it is and wait for a committer review.

Thanks Ilia, Chengpeng and Zsolt for the reviews.

Best regards,
Enrique.

El mié, 29 jul 2026 a las 1:38, Enrique Sánchez (<enriqueesanchz@gmail.com>) escribió:
Hi Chengpeng, thanks for the review!

On 26 Jul 2026 at 5:16, Chengpeng Yan (<chengpeng_yan@outlook.com>) wrote:
For patch 0001, apart from Ilia's comments, I only have one minor issue
with a comment in `mcv_can_cap()`:

Expressions are not supported, they can match multiple rows.

is not quite accurate. Matching multiple rows is not specific to
expressions; ordinary equality clauses may do so as well when they do
not fully constrain all dimensions. Expressions are excluded here
instead because the current full-coverage check only considers columns.

Other than that, patch 0001 looks good to me.

I've addressed the comments in the attached v7 patch. 

Regarding patch 0002, the formula seems reasonable as an estimate, but I
am not convinced that it can serve as an upper bound. Some non-MCV
combinations may be more frequent than the average, so using it as a cap
does not seem justified. It may be more or less accurate than the
existing per-column estimate depending on the data distribution.

Fair point, an average over the non-MCV combinations is not a true
upper bound, it's an estimation. I've been looking at how to reframe it
(it is essentially the same estimate var_eq_const() applies for single
columns on an MCV miss), but I think that discussion deserves its own
time (with a proper math analysis) and shouldn't hold back the rest.

So I'd propose we set 0002 aside for now and proceed with 0001, whose
reasoning is not affected by this: the least common MCV item is a
valid bound for any combination not in the list. I'll come back to
the ndistinct part in a follow-up.

Best regards,
Enrique. 
FAQ