Re: Optimize MCV stats for sortable types and utilize sorted-order properties

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

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Original
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: Sep 15, 2026 10:18
>To: pgsql-hackers 
>Subject: Optimize MCV stats for sortable types and utilize sorted-order properties
>......
>Optimize MCV stats for sortable types and utilize sorted-order properties.
>
>1.Preserve ascending-ordered MCV values for sort-comparable types when filling
>pg_statistic. In compute_scalar_stats(), retain existing logic and allocate
>extra ScalarMCVItem workspace to hold sorted MCV entries.
>
>2.When applying statistics, use the pre-sorted MCV list: 
>-compare against min/max boundaries. Boundary hits finish in 1-2 comparisons. 
>-Values inside MCV range use binary-search (average N/2 -> log(n)). 
>-Values outside MCV range skip full MCV iteration (N -> at most 2 comparisons).


Hi, hackers,

After investigating the files and functions related to STATISTIC_KIND_MCV, I classified their
roles (producer or consumer) and how MCV statistics are produced or consumed, as shown
in the list below (LIST-1). Taking third-party extensions and end users into consideration as well,
the consumers can be broadly classified as follows:
0. Final update of the statistics data:   attribute_statistics_update_internal()
1. Producers: compute_distinct_stats(), compute_scalar_stats(), and import_pg_statistic()
2. Consumers, which can be classified according to how they consume MCV statistics:
   2.1. Iterate through the MCV list, compare values using "=", and either select the selectivity
          of a matching value or accumulate selectivities.
   2.2. Ignore the values and only use the number of elements in the list/array, or unconditionally
          accumulate the selectivities.
   2.3. Only use the first element (the one with the highest selectivity).

After careful consideration, my initial proposal is as follows:
1. Add a new statistics kind:
   #define STATISTIC_KIND_MCV_VALUE_SORTED 8

Unlike STATISTIC_KIND_MCV, which is ordered by frequency, STATISTIC_KIND_MCV_VALUE_SORTED
stores MCVs ordered by their values.  STATISTIC_KIND_MCV_VALUE_SORTED and STATISTIC_KIND_MCV
will not coexist, so the number of statistics slots will not exceed the STATISTIC_NUM_SLOTS limit.

2. Only change the producer compute_scalar_stats() to generate the new MCV kind, STATISTIC_KIND_MCV_VALUE_SORTED.
   This should introduce almost no additional performance overhead (see the path/code snippet in my previous email). 
If STATISTIC_KIND_MCV already exists, it will be updated or replaced by STATISTIC_KIND_MCV_VALUE_SORTED.

3. Adjust the consumers described above as follows:
   2.1. Iterate through the MCV list, compare values using "=", and select the matching selectivity or accumulate selectivities.
        This is the more complicated case, which I discuss in detail below.
   2.2. Ignore the values and only use the number of elements in the list/array, or unconditionally accumulate selectivities.
           --> No change is required.
   2.3. Only use the first element (the one with the highest selectivity).
           --> Behavior needs to be adjusted:   iterate through numbers[] and find the maximum selectivity. 
                The performance impact should be controllable.

Here I would like to discuss case 2.1 in more detail: iterating through the MCV list, comparing values using "=", 
and selecting a matching selectivity or accumulating selectivities.
A. If a data type only has "=", the MCV statistics are generated by compute_distinct_stats().
   Therefore, only STATISTIC_KIND_MCV exists, and it can continue to be fetched and used in the existing way.

B. If a data type has both "=" and "<", prefer STATISTIC_KIND_MCV_VALUE_SORTED when fetching the MCV statistics.
   If it is not available, fall back to STATISTIC_KIND_MCV.
  2.1.1. If STATISTIC_KIND_MCV is available, use it exactly as before.
  2.1.2. If STATISTIC_KIND_MCV_VALUE_SORTED is available and the collations are equal, we can consider using
  the value ordering to optimize the lookup. For example:
    - First check whether the constant is within the range of the MCV values.
    - If it is within the range, use binary search to locate the matching value.
    - If it is outside the range, there is no need to compare it with every MCV value; we can directly use sumcommon.
  Otherwise, if the collations are not equalbe, have the same as with STATISTIC_KIND_MCV.

Case B will exist for a long time during upgrades/migration, because different tables may
have either STATISTIC_KIND_MCV_VALUE_SORTED or STATISTIC_KIND_MCV, unless this is a completely new database.

Based on my review of the relevant code and the function list in LIST-1, 
my current assessment is that this approach is feasible and that the associated risks appear manageable.

As discussed here and in my previous email, the potential benefit can be significant. 
In particular, var_eq_const() and mcv_selectivity() can greatly reduce the number of relatively expensive value comparisons. 
eqjoinsel() and get_variable_range() may also benefit significantly, although I have not analyzed them in detail yet.

My biggest concern, however, is third-party/extension consumers of STATISTIC_KIND_MCV. 
Their behavior is not something we can fully control or adjust at the PostgreSQL core level. 
Since the ordering of the MCV values would change, an extension may be relying on the first 
element being the MCV with the highest frequency, for example. Such assumptions could therefore be affected significantly.
I have not yet found a good solution for this potential compatibility issue.

These are my current thoughts and analysis. I would greatly appreciate any comments or suggestions.

Thanks again!

=== LIST-1 ===

src/backend/commands/analyze.c
  static void compute_distinct_stats() —   producer  ; generates MCV statistics for data types that only have the "=" operator.
  static void compute_scalar_stats() —   producer  ; generates MCV statistics for data types that have both "=" and "<" operators.

src/backend/executor/nodeHash.c
  static void ExecHashBuildSkewHash() —   consumer  ; reads the MCV list and iterates through it, accumulating sslot.numbers[i].

src/backend/statistics/attribute_stats.c
  static bool attribute_statistics_update_internal() —   producer  ; generates MCV statistics from the input parameters using statatt_build_stavalues() and updates the MCV statistics with statatt_set_slot().

src/backend/statistics/extended_stats_funcs.c
  static Datum import_pg_statistic() —   producer  ; generates MCV statistics from JSONB input.

src/backend/utils/adt/network_selfuncs.c
  static Selectivity networkjoinsel_inner() —   consumer  ; reads the MCV list and either accumulates mcv_numbers[i] or compares values for equality using "=".
  static Selectivity networkjoinsel_semi() —   consumer  ; reads the MCV list and either accumulates mcv_numbers[i] or compares values for equality using "=".

src/backend/utils/adt/selfuncs.c
  double var_eq_const() —   consumer  ; reads the MCV list, compares values using "=", obtains the selectivity of a matching value, and accumulates sslot.numbers when there is no match.
  double var_eq_non_const() —   consumer  ; reads the MCV statistics and currently uses sslot.numbers[0], i.e., the largest selectivity.
  double mcv_selectivity() —   consumer  ; reads the MCV list, checks each value against the comparison condition, and accumulates the corresponding selectivities.
  double ineq_histogram_selectivity() —   consumer  ; reads the MCV statistics but only uses mcvslot.nnumbers.
  Selectivity booltestsel() —   consumer  ; reads the first MCV element. If the first element is true, it uses sslot.numbers[0]; otherwise, it uses 1.0 - sslot.numbers[0] - freq_null.
  Datum eqjoinsel() —   consumer  ; apart from the hash algorithm, iterates through the MCV list and compares values using "=".
  void estimate_hash_bucket_stats() —   consumer  ; uses the first/largest-selectivity element by taking  mcv_freq = sslot.numbers[0].
  static bool get_variable_range() —   consumer  ; iterates through the MCV list and compares values using "=".



regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
I write
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: Sep 16, 2026 22:49
>To: pgsql-hackers 
>Cc: tgl , ilya.evdokimov 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>
>Original
>>From: ZizhuanLiu X-MAN <44973863@qq.com>
>>Date: Sep 15, 2026 10:18
>>To: pgsql-hackers 
>>Subject: Optimize MCV stats for sortable types and utilize sorted-order properties
>>......
>>Optimize MCV stats for sortable types and utilize sorted-order properties.
>>
>>1.Preserve ascending-ordered MCV values for sort-comparable types when filling
>>pg_statistic. In compute_scalar_stats(), retain existing logic and allocate
>>extra ScalarMCVItem workspace to hold sorted MCV entries.
>>
>>2.When applying statistics, use the pre-sorted MCV list: 
>>-compare against min/max boundaries. Boundary hits finish in 1-2 comparisons. 
>>-Values inside MCV range use binary-search (average N/2 -> log(n)). 
>>-Values outside MCV range skip full MCV iteration (N -> at most 2 comparisons).
>
>
>Hi, hackers,
>
>After investigating the files and functions related to STATISTIC_KIND_MCV, I classified their
>roles (producer or consumer) and how MCV statistics are produced or consumed, as shown
>in the list below (LIST-1). Taking third-party extensions and end users into consideration as well,
>the consumers can be broadly classified as follows:
>0. Final update of the statistics data:   attribute_statistics_update_internal()
>1. Producers: compute_distinct_stats(), compute_scalar_stats(), and import_pg_statistic()
>2. Consumers, which can be classified according to how they consume MCV statistics:
>   2.1. Iterate through the MCV list, compare values using "=", and either select the selectivity
>          of a matching value or accumulate selectivities.
>   2.2. Ignore the values and only use the number of elements in the list/array, or unconditionally
>          accumulate the selectivities.
>   2.3. Only use the first element (the one with the highest selectivity).
>
>After careful consideration, my initial proposal is as follows:
>1. Add a new statistics kind:
>   #define STATISTIC_KIND_MCV_VALUE_SORTED 8
>
>Unlike STATISTIC_KIND_MCV, which is ordered by frequency, STATISTIC_KIND_MCV_VALUE_SORTED
>stores MCVs ordered by their values.  STATISTIC_KIND_MCV_VALUE_SORTED and STATISTIC_KIND_MCV
>will not coexist, so the number of statistics slots will not exceed the STATISTIC_NUM_SLOTS limit.
>
>2. Only change the producer compute_scalar_stats() to generate the new MCV kind, STATISTIC_KIND_MCV_VALUE_SORTED.
>   This should introduce almost no additional performance overhead (see the path/code snippet in my previous email). 
>If STATISTIC_KIND_MCV already exists, it will be updated or replaced by STATISTIC_KIND_MCV_VALUE_SORTED.
>
>3. Adjust the consumers described above as follows:
>   2.1. Iterate through the MCV list, compare values using "=", and select the matching selectivity or accumulate selectivities.
>        This is the more complicated case, which I discuss in detail below.
>   2.2. Ignore the values and only use the number of elements in the list/array, or unconditionally accumulate selectivities.
>           --> No change is required.
>   2.3. Only use the first element (the one with the highest selectivity).
>           --> Behavior needs to be adjusted:   iterate through numbers[] and find the maximum selectivity. 
>                The performance impact should be controllable.
>
>Here I would like to discuss case 2.1 in more detail: iterating through the MCV list, comparing values using "=", 
>and selecting a matching selectivity or accumulating selectivities.
>A. If a data type only has "=", the MCV statistics are generated by compute_distinct_stats().
>   Therefore, only STATISTIC_KIND_MCV exists, and it can continue to be fetched and used in the existing way.
>
>B. If a data type has both "=" and "<", prefer STATISTIC_KIND_MCV_VALUE_SORTED when fetching the MCV statistics.
>   If it is not available, fall back to STATISTIC_KIND_MCV.
>  2.1.1. If STATISTIC_KIND_MCV is available, use it exactly as before.
>  2.1.2. If STATISTIC_KIND_MCV_VALUE_SORTED is available and the collations are equal, we can consider using
>  the value ordering to optimize the lookup. For example:
>    - First check whether the constant is within the range of the MCV values.
>    - If it is within the range, use binary search to locate the matching value.
>    - If it is outside the range, there is no need to compare it with every MCV value; we can directly use sumcommon.
>  Otherwise, if the collations are not equalbe, have the same as with STATISTIC_KIND_MCV.
>
>Case B will exist for a long time during upgrades/migration, because different tables may
>have either STATISTIC_KIND_MCV_VALUE_SORTED or STATISTIC_KIND_MCV, unless this is a completely new database.
>
>Based on my review of the relevant code and the function list in LIST-1, 
>my current assessment is that this approach is feasible and that the associated risks appear manageable.
>
>As discussed here and in my previous email, the potential benefit can be significant. 
>In particular, var_eq_const() and mcv_selectivity() can greatly reduce the number of relatively expensive value comparisons. 
>eqjoinsel() and get_variable_range() may also benefit significantly, although I have not analyzed them in detail yet.
>
>My biggest concern, however, is third-party/extension consumers of STATISTIC_KIND_MCV. 
>Their behavior is not something we can fully control or adjust at the PostgreSQL core level. 
>Since the ordering of the MCV values would change, an extension may be relying on the first 
>element being the MCV with the highest frequency, for example. Such assumptions could therefore be affected significantly.
>I have not yet found a good solution for this potential compatibility issue.

There is another fundamental issue:
    If the new-version compute_scalar_stats() no longer generates STATISTIC_KIND_MCV, but third-party code or extensions try to fetch STATISTIC_KIND_MCV.  When only STATISTIC_KIND_MCV_VALUE_SORTED exists in the system, 
    - should get_attstatsslot() re-sort STATISTIC_KIND_MCV_VALUE_SORTED by numbers[] in ascending order before returning it to the caller?
           (This re-sort cost should be manageable, since we sort on numbers[], not on values[].)
    - Or should we return STATISTIC_KIND_MCV_VALUE_SORTED directly without any processing?

For good backward-compatibility, I lean toward the former option, though it is not a very elegant design.

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
>I write
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: Sep 17, 2026 10:01
>To: ZizhuanLiu X-MAN <44973863@qq.com>, pgsql-hackers 
>Cc: tgl , ilya.evdokimov 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>......
>There is another fundamental issue:
>    If the new-version compute_scalar_stats() no longer generates STATISTIC_KIND_MCV, but third-party code or extensions try to fetch STATISTIC_KIND_MCV.  When only STATISTIC_KIND_MCV_VALUE_SORTED exists in the system, 
>    - should get_attstatsslot() re-sort STATISTIC_KIND_MCV_VALUE_SORTED by numbers[] in ascending order before returning it to the caller?
>           (This re-sort cost should be manageable, since we sort on numbers[], not on values[].)
>    - Or should we return STATISTIC_KIND_MCV_VALUE_SORTED directly without any processing?
>
>For good backward-compatibility, I lean toward the former option, though it is not a very elegant design.


Looking at the call graph in LIST-1: 
  When a caller requests STATISTIC_KIND_MCV but only STATISTIC_KIND_MCV_VALUE_SORTED is available in the system,
some reordering is required.

Based on how these callers consume the data, we only need to swap the entry with the largest number[i] and its
corresponding values[i] into slot [0], **rather than performing a full sort of the entire array**.

As shown by the logic in LIST-1: existing callers either rely on slot [0] holding the entry with the highest count
 (the original behaviour of STATISTIC_KIND_MCV), or iterate over the number[] / values[] arrays.

Simply swapping the maximum-count entry to index [0] is sufficient to preserve backward compatibility. This keeps
the adjustment minimal: it requires N comparisons over the double-typed number[] array and at most one two-element swap,
so the overhead is kept as small as possible.

I will go ahead and implement along these lines. Deep insights and further feedback are very welcome.


>=== LIST-1 ===                                                                                                                                                                                                  
>                                                                                                                                                                                                                
>src/backend/commands/analyze.c                                                                                                                                                                                  
>  static void compute_distinct_stats() —   producer  ; generates MCV statistics for data types that only have the "=" operator.                                                                                
>  static void compute_scalar_stats() —   producer  ; generates MCV statistics for data types that have both "=" and "<" operators.                                                                             
>                                                                                                                                                                                                                
>src/backend/executor/nodeHash.c                                                                                                                                                                                 
>  static void ExecHashBuildSkewHash() —   consumer  ; reads the MCV list and iterates through it, accumulating sslot.numbers[i].                                                                               
>                                                                                                                                                                                                                
>src/backend/statistics/attribute_stats.c                                                                                                                                                                        
>  static bool attribute_statistics_update_internal() —   producer  ; generates MCV statistics from the input parameters using statatt_build_stavalues() and updates the MCV statistics with statatt_set_slot().
>                                                                                                                                                                                                                
>src/backend/statistics/extended_stats_funcs.c                                                                                                                                                                   
>  static Datum import_pg_statistic() —   producer  ; generates MCV statistics from JSONB input.                                                                                                                
>                                                                                                                                                                                                                
>src/backend/utils/adt/network_selfuncs.c                                                                                                                                                                        
>  static Selectivity networkjoinsel_inner() —   consumer  ; reads the MCV list and either accumulates mcv_numbers[i] or compares values for equality using "=".                                                
>  static Selectivity networkjoinsel_semi() —   consumer  ; reads the MCV list and either accumulates mcv_numbers[i] or compares values for equality using "=".                                                 
>                                                                                                                                                                                                                
>src/backend/utils/adt/selfuncs.c                                                                                                                                                                                
>  double var_eq_const() —   consumer  ; reads the MCV list, compares values using "=", obtains the selectivity of a matching value, and accumulates sslot.numbers when there is no match.                      
>  double var_eq_non_const() —   consumer  ; reads the MCV statistics and currently uses sslot.numbers[0], i.e., the largest selectivity.                                                                       
>  double mcv_selectivity() —   consumer  ; reads the MCV list, checks each value against the comparison condition, and accumulates the corresponding selectivities.                                            
>  double ineq_histogram_selectivity() —   consumer  ; reads the MCV statistics but only uses mcvslot.nnumbers.                                                                                                 
>  Selectivity booltestsel() —   consumer  ; reads the first MCV element. If the first element is true, it uses sslot.numbers[0]; otherwise, it uses 1.0 - sslot.numbers[0] - freq_null.                        
>  Datum eqjoinsel() —   consumer  ; apart from the hash algorithm, iterates through the MCV list and compares values using "=".                                                                                
>  void estimate_hash_bucket_stats() —   consumer  ; uses the first/largest-selectivity element by taking  mcv_freq = sslot.numbers[0].                                                                         
>  static bool get_variable_range() —   consumer  ; iterates through the MCV list and compares values using "=".      

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi, hackers

Optimize MCV statistics for sortable types by leveraging sorted-order properties

1. Preserve ascending-ordered MCV values (new statistic kind STATISTIC_KIND_MCV_VALUE_SORTED)
for sort-comparable types when populating pg_statistic.
In compute_scalar_stats(), keep existing logic and allocate an extra ScalarMCVItem
workspace to store sorted MCV entries.

2. Use the pre-sorted MCV list during selectivity estimation:
   - Check against min/max boundaries; boundary cases complete with only 1-2 comparisons.
   - Entries inside the MCV range use binary search, reducing cost from average N/2 to log(N).
   - Entries outside the MCV range skip full MCV iteration, limiting comparisons to at most 2.

   This optimization is implemented for **var_eq_const()** (equality comparisons) and
   **mcv_selectivity()** (inequalities: <, <=, >, >=), fully exploiting sorted MCV properties.
   Further functions that can benefit from sorted MCV will be considered later.

3. Completed work:
   - Compatibility support for non-sortable types and sorted-state detection.
   - pg_stats view updates to expose STATISTIC_KIND_MCV_VALUE_SORTED MCV values
     via most_common_vals and most_common_freqs.

4. TODO:
   - Avoid storing STATISTIC_KIND_MCV_VALUE_SORTED alongside legacy STATISTIC_KIND_MCV.
     When compute_scalar_stats() generates the new sorted MCV for sortable types,
     remove or overwrite any existing STATISTIC_KIND_MCV entry.
   - Audit functions for performance benefits or regressions introduced by sorted MCV,
     and apply necessary fixes.
  - Add comparison of performance test results



Attach test SQL and patch files:

drop table if exists t_analyze_mcv;
create table t_analyze_mcv(id int);

insert into t_analyze_mcv select (g+45) % 10 from generate_series(1, 90) g;
insert into t_analyze_mcv select 12 from generate_series(1, 10) g;
insert into t_analyze_mcv select * from t_analyze_mcv;

analyze t_analyze_mcv;

select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename = 't_analyze_mcv'\gx


-[ RECORD 1 ]-----+--------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | 11
most_common_vals  | {0,1,2,3,4,5,6,7,8,9,12}
most_common_freqs | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
correlation       | 0.20327759

xman7=# select id,count(*) from t_analyze_mcv group by id ;
 id | count
----+-------
  8 |    18
  9 |    18
  7 |    18
  1 |    18
  5 |    18
  4 |    18
  2 |    18
  0 |    18
  6 |    18
 12 |    20
  3 |    18
(11 rows)

xman7=#

--for var_eq_const()
explain select * from t_analyze_mcv where id = -1;   --1  rows,  low-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES
explain select * from t_analyze_mcv where id = 0;    --18 rows,  compare first one,directly complete
explain select * from t_analyze_mcv where id = 5;    --18 rows,  in mcv rang,one of list,binary search found
explain select * from t_analyze_mcv where id = 10;   --1  rows,  in mcv rang,one of list,binary search not found, directly compute sumcommon with comparing OTHER MCV VALUES
explain select * from t_analyze_mcv where id = 12;   --20 rows,  compare last one,directly complete
explain select * from t_analyze_mcv where id = 13;   --1  rows,  high-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES

--for mcv_selectivity()

--< <=
-- 1 row, low-out-of-mcv-range, 1 compare with [0]. Directly compute sumcommon without comparing other MCV values; mcv_selec = 0.0
explain select * from t_analyze_mcv where id <  -1; -- 1 rows
--or
explain select * from t_analyze_mcv where id <= -1; -- 1 rows

-- 1 compare with [0]. Directly compute sumcommon without comparing other MCV values;
explain select * from t_analyze_mcv where id <  0; -- 1 rows
--or
explain select * from t_analyze_mcv where id <= 0; -- 18 rows

-- compare with [0] and [nvlaues - 1], and binary search
explain select * from t_analyze_mcv where id <  1; -- 18 rows
explain select * from t_analyze_mcv where id <= 1; --36 rows
explain select * from t_analyze_mcv where id <  10; --180 rows
explain select * from t_analyze_mcv where id <= 10; --180 rows

-- compare with [0] and [nvlaues - 1], not need binary search
explain select * from t_analyze_mcv where id <  12; --180 rows
explain select * from t_analyze_mcv where id <= 12; --200 rows

-- compare with [0] and [nvlaues - 1], not need binary search
explain select * from t_analyze_mcv where id <  12; --1 rows
explain select * from t_analyze_mcv where id <= 12; --1 rows

--> >=
--only compare with [0] and and [nvlaues - 1],not need binary search
explain select * from t_analyze_mcv where id > -1;  --200 rows
explain select * from t_analyze_mcv where id >= -1; --200 row
explain select * from t_analyze_mcv where id > 0;  --182 rows
explain select * from t_analyze_mcv where id >= 0; --200 rows

--only compare with [0] and and [nvlaues - 1],and binary search
explain select * from t_analyze_mcv where id > 5;  -- 92 rows
explain select * from t_analyze_mcv where id >= 5; -- 110 rows

--only compare with [nvlaues - 1]
explain select * from t_analyze_mcv where id > 12;  -- 1 rows
explain select * from t_analyze_mcv where id >= 12;

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi, hackers

(Rebase it.     CC’ing all, hoping for your sincere assistance.)

Optimize MCV statistics for sortable types by leveraging sorted-order properties

1. Preserve ascending-ordered MCV values (new statistic kind STATISTIC_KIND_MCV_VALUE_SORTED)
for sort-comparable types when populating pg_statistic.
In compute_scalar_stats(), keep existing logic and allocate an extra ScalarMCVItem
workspace to store sorted MCV entries.

2. Use the pre-sorted MCV list during selectivity estimation:
   - Check against min/max boundaries; boundary cases complete with only 1-2 comparisons.
   - Entries inside the MCV range use binary search, reducing cost from average N/2 to log(N).
   - Entries outside the MCV range skip full MCV iteration, limiting comparisons to at most 2.

   This optimization is implemented for **var_eq_const()** (equality comparisons) and
   **mcv_selectivity()** (inequalities: <, <=, >, >=), fully exploiting sorted MCV properties.
   Further functions that can benefit from sorted MCV will be considered later.

3. Completed work:
   - Compatibility support for non-sortable types and sorted-state detection.
   - pg_stats view updates to expose STATISTIC_KIND_MCV_VALUE_SORTED MCV values
     via most_common_vals and most_common_freqs.

4. TODO:
   - Avoid storing STATISTIC_KIND_MCV_VALUE_SORTED alongside legacy STATISTIC_KIND_MCV.
     When compute_scalar_stats() generates the new sorted MCV for sortable types,
     remove or overwrite any existing STATISTIC_KIND_MCV entry.
   - Audit functions for performance benefits or regressions introduced by sorted MCV,
     and apply necessary fixes.
  - Add comparison of performance test results.


Attach test SQL and patch files:
drop table if exists t_analyze_mcv;
create table t_analyze_mcv(id int);
insert into t_analyze_mcv select (g+45) % 10 from generate_series(1, 90) g;
insert into t_analyze_mcv select 12 from generate_series(1, 10) g;
insert into t_analyze_mcv select * from t_analyze_mcv;
analyze t_analyze_mcv;
select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename = 't_analyze_mcv'\gx
-[ RECORD 1 ]-----+--------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | 11
most_common_vals  | {0,1,2,3,4,5,6,7,8,9,12}
most_common_freqs | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
correlation       | 0.20327759
xman7=# select id,count(*) from t_analyze_mcv group by id ;
 id | count
----+-------
  8 |    18
  9 |    18
  7 |    18
  1 |    18
  5 |    18
  4 |    18
  2 |    18
  0 |    18
  6 |    18
 12 |    20
  3 |    18
(11 rows)
xman7=#
--for var_eq_const()
explain select * from t_analyze_mcv where id = -1;   --1  rows,  low-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES
explain select * from t_analyze_mcv where id = 0;    --18 rows,  compare first one,directly complete
explain select * from t_analyze_mcv where id = 5;    --18 rows,  in mcv rang,one of list,binary search found
explain select * from t_analyze_mcv where id = 10;   --1  rows,  in mcv rang,one of list,binary search not found, directly compute sumcommon with comparing OTHER MCV VALUES
explain select * from t_analyze_mcv where id = 12;   --20 rows,  compare last one,directly complete
explain select * from t_analyze_mcv where id = 13;   --1  rows,  high-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES
--for mcv_selectivity()
--< <=
-- 1 row, low-out-of-mcv-range, 1 compare with [0]. Directly compute sumcommon without comparing other MCV values; mcv_selec = 0.0
explain select * from t_analyze_mcv where id <  -1; -- 1 rows
--or
explain select * from t_analyze_mcv where id <= -1; -- 1 rows
-- 1 compare with [0]. Directly compute sumcommon without comparing other MCV values;
explain select * from t_analyze_mcv where id <  0; -- 1 rows
--or
explain select * from t_analyze_mcv where id <= 0; -- 18 rows
-- compare with [0] and [nvlaues - 1], and binary search
explain select * from t_analyze_mcv where id <  1; -- 18 rows
explain select * from t_analyze_mcv where id <= 1; --36 rows
explain select * from t_analyze_mcv where id <  10; --180 rows
explain select * from t_analyze_mcv where id <= 10; --180 rows
-- compare with [0] and [nvlaues - 1], not need binary search
explain select * from t_analyze_mcv where id <  12; --180 rows
explain select * from t_analyze_mcv where id <= 12; --200 rows
-- compare with [0] and [nvlaues - 1], not need binary search
explain select * from t_analyze_mcv where id <  12; --1 rows
explain select * from t_analyze_mcv where id <= 12; --1 rows
--> >=
--only compare with [0] and and [nvlaues - 1],not need binary search
explain select * from t_analyze_mcv where id > -1;  --200 rows
explain select * from t_analyze_mcv where id >= -1; --200 row
explain select * from t_analyze_mcv where id > 0;  --182 rows
explain select * from t_analyze_mcv where id >= 0; --200 rows
--only compare with [0] and and [nvlaues - 1],and binary search
explain select * from t_analyze_mcv where id > 5;  -- 92 rows
explain select * from t_analyze_mcv where id >= 5; -- 110 rows
--only compare with [nvlaues - 1]
explain select * from t_analyze_mcv where id > 12;  -- 1 rows
explain select * from t_analyze_mcv where id >= 12;
regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

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

On 9/21/26 08:40, ZizhuanLiu X-MAN wrote:
> Hi, hackers
>
> (Rebase it.     CC’ing all, hoping for your sincere assistance.)
>
> Optimize MCV statistics for sortable types by leveraging sorted-order properties
>
> 1. Preserve ascending-ordered MCV values (new statistic kind STATISTIC_KIND_MCV_VALUE_SORTED)
> for sort-comparable types when populating pg_statistic.
> In compute_scalar_stats(), keep existing logic and allocate an extra ScalarMCVItem
> workspace to store sorted MCV entries.
>
> 2. Use the pre-sorted MCV list during selectivity estimation:
>     - Check against min/max boundaries; boundary cases complete with only 1-2 comparisons.
>     - Entries inside the MCV range use binary search, reducing cost from average N/2 to log(N).
>     - Entries outside the MCV range skip full MCV iteration, limiting comparisons to at most 2.
>
>     This optimization is implemented for **var_eq_const()** (equality comparisons) and
>     **mcv_selectivity()** (inequalities: <, <=, >, >=), fully exploiting sorted MCV properties.
>     Further functions that can benefit from sorted MCV will be considered later.
>
> 3. Completed work:
>     - Compatibility support for non-sortable types and sorted-state detection.
>     - pg_stats view updates to expose STATISTIC_KIND_MCV_VALUE_SORTED MCV values
>       via most_common_vals and most_common_freqs.
>
> 4. TODO:
>     - Avoid storing STATISTIC_KIND_MCV_VALUE_SORTED alongside legacy STATISTIC_KIND_MCV.
>       When compute_scalar_stats() generates the new sorted MCV for sortable types,
>       remove or overwrite any existing STATISTIC_KIND_MCV entry.
>     - Audit functions for performance benefits or regressions introduced by sorted MCV,
>       and apply necessary fixes.
>    - Add comparison of performance test results.
>
>
> Attach test SQL and patch files:
> drop table if exists t_analyze_mcv;
> create table t_analyze_mcv(id int);
> insert into t_analyze_mcv select (g+45) % 10 from generate_series(1, 90) g;
> insert into t_analyze_mcv select 12 from generate_series(1, 10) g;
> insert into t_analyze_mcv select * from t_analyze_mcv;
> analyze t_analyze_mcv;
> select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
>   from pg_catalog.pg_stats where tablename = 't_analyze_mcv'\gx
> -[ RECORD 1 ]-----+--------------------------------------------------------
> attname           | id
> null_frac         | 0
> n_distinct        | 11
> most_common_vals  | {0,1,2,3,4,5,6,7,8,9,12}
> most_common_freqs | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
> correlation       | 0.20327759
> xman7=# select id,count(*) from t_analyze_mcv group by id ;
>   id | count
> ----+-------
>    8 |    18
>    9 |    18
>    7 |    18
>    1 |    18
>    5 |    18
>    4 |    18
>    2 |    18
>    0 |    18
>    6 |    18
>   12 |    20
>    3 |    18
> (11 rows)
> xman7=#
> --for var_eq_const()
> explain select * from t_analyze_mcv where id = -1;   --1  rows,  low-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES
> explain select * from t_analyze_mcv where id = 0;    --18 rows,  compare first one,directly complete
> explain select * from t_analyze_mcv where id = 5;    --18 rows,  in mcv rang,one of list,binary search found
> explain select * from t_analyze_mcv where id = 10;   --1  rows,  in mcv rang,one of list,binary search not found, directly compute sumcommon with comparing OTHER MCV VALUES
> explain select * from t_analyze_mcv where id = 12;   --20 rows,  compare last one,directly complete
> explain select * from t_analyze_mcv where id = 13;   --1  rows,  high-out-off-mcv-range, directly compute sumcommon with comparing OTHER MCV VALUES
> --for mcv_selectivity()
> --< <=
> -- 1 row, low-out-of-mcv-range, 1 compare with [0]. Directly compute sumcommon without comparing other MCV values; mcv_selec = 0.0
> explain select * from t_analyze_mcv where id <  -1; -- 1 rows
> --or
> explain select * from t_analyze_mcv where id <= -1; -- 1 rows
> -- 1 compare with [0]. Directly compute sumcommon without comparing other MCV values;
> explain select * from t_analyze_mcv where id <  0; -- 1 rows
> --or
> explain select * from t_analyze_mcv where id <= 0; -- 18 rows
> -- compare with [0] and [nvlaues - 1], and binary search
> explain select * from t_analyze_mcv where id <  1; -- 18 rows
> explain select * from t_analyze_mcv where id <= 1; --36 rows
> explain select * from t_analyze_mcv where id <  10; --180 rows
> explain select * from t_analyze_mcv where id <= 10; --180 rows
> -- compare with [0] and [nvlaues - 1], not need binary search
> explain select * from t_analyze_mcv where id <  12; --180 rows
> explain select * from t_analyze_mcv where id <= 12; --200 rows
> -- compare with [0] and [nvlaues - 1], not need binary search
> explain select * from t_analyze_mcv where id <  12; --1 rows
> explain select * from t_analyze_mcv where id <= 12; --1 rows
> --> >=
> --only compare with [0] and and [nvlaues - 1],not need binary search
> explain select * from t_analyze_mcv where id > -1;  --200 rows
> explain select * from t_analyze_mcv where id >= -1; --200 row
> explain select * from t_analyze_mcv where id > 0;  --182 rows
> explain select * from t_analyze_mcv where id >= 0; --200 rows
> --only compare with [0] and and [nvlaues - 1],and binary search
> explain select * from t_analyze_mcv where id > 5;  -- 92 rows
> explain select * from t_analyze_mcv where id >= 5; -- 110 rows
> --only compare with [nvlaues - 1]
> explain select * from t_analyze_mcv where id > 12;  -- 1 rows
> explain select * from t_analyze_mcv where id >= 12;
> regards,
> --
> ZizhuanLiu (X-MAN)
> 44973863@qq.com

In practice, users rarely bump default_statistics_target to extreme 
values like 10 000. At 100-200, scanning a compact array of Datums fits 
entirely in L1 cache.

Furthermore, introducing a new STATISTIC_KIND fractures the catalog and 
consumes limited slots in pg_statistics for an optimization targeting a 
rare worst-case scenario. Range estimation is already the dedicated 
responsibility of histogram_BOUNDS, so having MCV duplicate sorted range 
checks adds considerable code complexity to selfuncs.c with very 
questionable gains.

To sum it up, keeping the status quo is the better choice.

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



Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Original
>From: Ilia Evdokimov 
>Date: Sep 21, 2026 21:03
>To: ZizhuanLiu X-MAN <44973863@qq.com>, pgsql-hackers 
>Cc: tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>......
>In practice, users rarely bump default_statistics_target to extreme 
>values like 10 000. At 100-200, scanning a compact array of Datums fits 
>entirely in L1 cache.

1.Regarding the L1 cache aspect, I have not studied it in much depth. After doing some additional research, 
I would like to share a few thoughts:

Regardless of whether default_statistics_target is the maximum value of 10,000 or the default value of 100,
across an entire database system, there can be a very large number of columns that may use comparison
operators for selectivity estimation, depending on the SQL workload. var_eq_const() handles =, while
mcv_selectivity() handles <, <=, > and >=.

These comparison operators are very common and can be used very frequently. The proposed approach
could significantly reduce the number of comparisons/scans from an average of N/2 for = and a fixed N
for <, <=, > and >=, to approximately log2(N) by using binary search. If the CONSTVALUE is close to one
of the boundaries of the sorted values, the number of comparisons may potentially be reduced to the
minimum of just one or two.

For example:

var_eq_const():
                                                 Original                       Proposed 
default_statistics_target  min   max     avg          min   max    avg
-------------------------------------------------------------------
100                                    1       100      50            1        7        5.8
10000                               1       10000  5000        1       14      12.36
-------------------------------------------------------------------

mcv_selectivity():
                                           Original             Proposed 
default_statistics_target  fixed             min   max    avg
------------------------------------------------------------
100                                    100               1        7         5.8
10000                               10000           1        14       12.36
------------------------------------------------------------

These numbers are only intended to illustrate the reduction in the number of comparisons; 
they are not intended to represent measured CPU execution time.

2.Regarding the statement that "a compact array of Datums fits entirely in L1 cache": 
L1 cache is a very limited and valuable resource, and part of it is used for instruction caching
rather than being entirely available for data. Therefore, I think it is still useful to consider the
amount of work performed on the cached data.

The goal of this proposal is to reduce the number of scans and comparisons, complete the
required work as quickly as possible, and release the relevant cache resources as soon as
possible so that they can be used by other concurrent work.

3.Since the capacity of L1 cache is limited, even if part or all of the data is cached, there can still
be cases where the mcv values[] array is too large to fit entirely in L1 cache. In addition, for
variable-length data types such as text, the comparison itself can be relatively expensive. 
Therefore, reducing the number of comparisons may be even more important in these cases,
as it can significantly reduce the time required for selectivity estimation.

4.In addition, even for commonly used data types such as int, reducing the number of scans/comparisons
also reduces the subsequent function-call overhead and potentially other memory-related overhead
associated with performing the comparisons.

5.From the global perspective of the DBMS and OS, making efficient use of the most limited resources and
releasing them as early as possible is also a useful high-level design principle for improving concurrency.

6.Even if we focus only on these one or two functions themselves, I think the potential benefit is already fairly clear.
These are frequently used and performance-sensitive parts of the selectivity estimation path, and a large number of
columns may potentially go through them. When combined with concurrent workloads across the DBMS and OS, 
the cumulative benefit could be significant.

I think this reduction in the number of scans/comparisons is one of the main potential improvements and benefits of this approach.



>Furthermore, introducing a new STATISTIC_KIND fractures the catalog and 
>consumes limited slots in pg_statistics for an optimization targeting a 
>rare worst-case scenario. Range estimation is already the dedicated 

>>From: ZizhuanLiu X-MAN <44973863@qq.com>
>>Date: Sep 16, 2026 22:49
>>To: pgsql-hackers 
>>Cc: tgl , ilya.evdokimov 
>>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>>......
>>STATISTIC_KIND_MCV_VALUE_SORTED and STATISTIC_KIND_MCV
>>will not coexist, so the number of statistics slots will not exceed the STATISTIC_NUM_SLOTS limit."

1.When analyzing a table, for data types without a < operator, compute_distinct_stats() continues to
generate the existing MCV statistics, where the values[] cannot necessarily be sorted by value, but the
numbers[] are sorted in descending order of frequency.

For data types with a < operator, the original compute_scalar_stats() generates MCV statistics with
numbers[] sorted in descending order of frequency, while the new version generates MCV statistics
with values[] sorted in ascending order of value. The change to this function is relatively small: 
it mainly adds a palloc_array(ScalarMCVItem, num_mcv) allocation, without introducing other
significant computation. These two forms will not coexist for sortable columns.

(TODO: this part is not completed yet. I will continue working on it later: the new version will replace
the old statistics for this type of column.) Therefore, there should be no conflict, and the number of
statistics slots will not exceed the STATISTIC_NUM_SLOTS limit.

2.pg_stats had been adjusted to treat STATISTIC_KIND_MCV and STATISTIC_KIND_MCV_VALUE_SORTED
in the same way when returning most_common_vals and most_common_freqs.

This is currently the only compatibility concern I have identified: an SQL caller may access most_common_freqs[0]
and assume that it represents the maximum frequency, which is related to the next point.

3.For consumers that currently directly use numbers[0] as the maximum MCV selectivity, we can encapsulate this
behavior in a compatibility helper such as max_mcv_numbers(&sslot, statskind).

4.This is the compatibility and discoverability approach I have considered so far for retaining compatibility while
allowing MCV values to be stored in value order. I think this addresses the concern you raised, but I would be very
interested to hear if there are other compatibility issues that I have overlooked.



>rare worst-case scenario. Range estimation is already the dedicated 
>responsibility of histogram_BOUNDS, so having MCV duplicate sorted range 
>checks adds considerable code complexity to selfuncs.c with very 
>questionable gains.
>To sum it up, keeping the status quo is the better choice.

1.Based on my investigation, comparison operators cover a fairly broad class of commonly used selectivity estimation paths. 
ar_eq_const() handles =, while mcv_selectivity() handles <, <=, > and >=:

 * var_eq_const --- eqsel for var = const case
 *	scalarineqsel		- Selectivity of "<", "<=", ">", ">=" for scalars.
 *	scalarltsel		- Selectivity of "<" for scalars.
 *	scalarlesel		- Selectivity of "<=" for scalars.
 *	scalargtsel		- Selectivity of ">" for scalars.
 *	scalargesel		- Selectivity of ">=" for scalars.

In particular, mcv_selectivity() performs selectivity estimation for an individual range comparison.

I have not yet carefully investigated cases where these operators are combined with AND, or BETWEEN conditions.
I do not yet know whether these cases can also benefit from the value ordering of the new MCV array. This is one of
the areas I plan to investigate next, and I suspect there may be opportunities to make use of the sorted values[] there as well.

2.Regarding the existing STATISTIC_KIND_HISTOGRAM comment:
 * stanumbers is not used and should be NULL.  IMPORTANT POINT: if an MCV
 * slot is also provided, then the histogram describes the data distribution
 * *after removing the values listed in MCV* (thus, it's a "compressed
 * histogram" in the technical parlance).  This allows a more accurate
 * representation of the distribution of a column with some very-common
 * values.  In a column with only a few distinct values, it's possible that
 * the MCV list describes the entire data population; in this case the
 * histogram reduces to empty and should be omitted.

My understanding is that MCV and STATISTIC_KIND_HISTOGRAM are therefore not duplicating the same information. 
In fact, STATISTIC_KIND_HISTOGRAM may not exist at all in some cases.

Therefore, I think an MCV list sorted by values[] is not redundant storage, but can provide independent value for
efficiently locating and processing the MCV portion of the distribution.

3.Looking at the V2 patch, because it takes binary search into account, makes use of the comparison results against
the two boundary elements of the array, and also needs to handle the = cases within <= and >=, the current code logic,
readability, and maintainability may not yet be optimal.

If there is an opportunity, I think this part could be further simplified or refactored into an independent helper function to
encapsulate the relevant checks.
>--
>Best regards,
>Ilia Evdokimov,
>Tantor Labs LLC,
>https://tantorlabs.com/


These are my current thoughts and observations. 
I may certainly have overlooked some aspects,so I would welcome any corrections or suggestions.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Original
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-09-22 12:07
>To: Ilia Evdokimov , pgsql-hackers 
>Cc: tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>
>Original
>>From: Ilia Evdokimov 
>>Date: Sep 21, 2026 21:03
>>To: ZizhuanLiu X-MAN <44973863@qq.com>, pgsql-hackers 
>>Cc: tgl , tomas , dean.a.rasheed , guofenglinux 
>>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>>......
>>In practice, users rarely bump default_statistics_target to extreme 
>>values like 10 000. At 100-200, scanning a compact array of Datums fits 
>>entirely in L1 cache.
>......
>For data types with a < operator, the original compute_scalar_stats() generates MCV statistics with
>numbers[] sorted in descending order of frequency, while the new version generates MCV statistics
>with values[] sorted in ascending order of value. The change to this function is relatively small: 
>it mainly adds a palloc_array(ScalarMCVItem, num_mcv) allocation, without introducing other
>significant computation. These two forms will not coexist for sortable columns.
>
>(TODO: this part is not completed yet. I will continue working on it later: the new version will replace
>the old statistics for this type of column.) Therefore, there should be no conflict, and the number of
>statistics slots will not exceed the STATISTIC_NUM_SLOTS limit.

After investigation, statistics for columns/index expressions/extended expressions stored in
pg_catalog.pg_statistic are overwritten as a whole. 

Therefore the note below:*"TODO: this part is not completed yet. I will continue working on
it later: the new version will replace the old statistics for this type of column."* is no longer a
concern and can be dropped from consideration.

I have attached the verification SQL statements together with their results at the end:
xman7=# \d
           List of relations
 Schema |     Name      | Type  | Owner 
--------+---------------+-------+-------
 public | t_analyze_mcv | table | xman
(1 row)

xman7=# select oid from pg_catalog.pg_class where relname = 't_analyze_mcv';
  oid  
-------
 16385
(1 row)

xman7=# select * from pg_catalog.pg_statistic where starelid = 16385\gx
-[ RECORD 1 ]--------------------------------------------------------
starelid    | 16385
staattnum   | 1
stainherit  | f
stanullfrac | 0
stawidth    | 4
stadistinct | 11
stakind1    | 8     =#define STATISTIC_KIND_MCV_VALUE_SORTED  8
stakind2    | 3
stakind3    | 0
stakind4    | 0
stakind5    | 0
staop1      | 96
staop2      | 97
staop3      | 0
staop4      | 0
staop5      | 0
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
stanumbers2 | {0.20327759}
stanumbers3 | 
stanumbers4 | 
stanumbers5 | 
stavalues1  | {0,1,2,3,4,5,6,7,8,9,12}
stavalues2  | 
stavalues3  | 
stavalues4  | 
stavalues5  | 


xman7=#  update pg_catalog.pg_statistic set  stakind1= 1 where starelid = 16385;
UPDATE 1
xman7=# select * from pg_catalog.pg_statistic where starelid = 16385\gx
-[ RECORD 1 ]--------------------------------------------------------
starelid    | 16385
staattnum   | 1
stainherit  | f
stanullfrac | 0
stawidth    | 4
stadistinct | 11
stakind1    | 1   =====#define STATISTIC_KIND_MCV	1
stakind2    | 3
stakind3    | 0
stakind4    | 0
stakind5    | 0
staop1      | 96
staop2      | 97
staop3      | 0
staop4      | 0
staop5      | 0
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
stanumbers2 | {0.20327759}
stanumbers3 | 
stanumbers4 | 
stanumbers5 | 
stavalues1  | {0,1,2,3,4,5,6,7,8,9,12}
stavalues2  | 
stavalues3  | 
stavalues4  | 
stavalues5  | 

xman7=# select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename = 't_analyze_mcv'\gx
-[ RECORD 1 ]-----+--------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | 11
most_common_vals  | {0,1,2,3,4,5,6,7,8,9,12}
most_common_freqs | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
correlation       | 0.20327759

xman7=# 


xman7=# analyze t_analyze_mcv;
ANALYZE
xman7=# select * from pg_catalog.pg_statistic where starelid = 16385\gx
-[ RECORD 1 ]--------------------------------------------------------
starelid    | 16385
staattnum   | 1
stainherit  | f
stanullfrac | 0
stawidth    | 4
stadistinct | 11
stakind1    | 8    =#define STATISTIC_KIND_MCV_VALUE_SORTED  8
stakind2    | 3
stakind3    | 0
stakind4    | 0
stakind5    | 0
staop1      | 96
staop2      | 97
staop3      | 0
staop4      | 0
staop5      | 0
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
stanumbers2 | {0.20327759}
stanumbers3 | 
stanumbers4 | 
stanumbers5 | 
stavalues1  | {0,1,2,3,4,5,6,7,8,9,12}
stavalues2  | 
stavalues3  | 
stavalues4  | 
stavalues5  | 

xman7=# select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename = 't_analyze_mcv'\gx
-[ RECORD 1 ]-----+--------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | 11
most_common_vals  | {0,1,2,3,4,5,6,7,8,9,12}
most_common_freqs | {0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.09,0.1}
correlation       | 0.20327759

xman7=# 



regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi, hackers

mergejoinscansel() calls get_variable_range() for both inner and outer relations to
retrieve the minimum and maximum values of values[].

In the following code snippet inside get_variable_range(), when STATISTIC_KIND_MCV_VALUE_SORTED
is present, we can avoid the O(n) comparisons on the MCV value[] performed by get_stats_slot_range().

**This optimization eliminates all N comparisons entirely.**

```C
/*
			 * Like STATISTIC_KIND_HISTOGRAM: if the MCV slot is
			 * STATISTIC_KIND_MCV_VALUE_SORTED, it has the ordering we want,
			 * grab the last and first values.
			 */
			if (sslot.stacoll == collation && sslot.nvalues > 0 &&
				statskind == STATISTIC_KIND_MCV_VALUE_SORTED)
			{
				tmin = datumCopy(sslot.values[0], typByVal, typLen);
				tmax = datumCopy(sslot.values[sslot.nvalues - 1], typByVal, typLen);
				have_data = true;
			}
      else
				get_stats_slot_range(&sslot, opfuncoid, &opproc,
									 collation, typLen, typByVal,
									 &tmin, &tmax, &have_data);
```C


Below are the test SQL statements and their results:
```SQL
drop table if exists t1;
create table t1(id int);
drop table if exists t2;
create table t2(id int);
insert into t1 select oid  from pg_catalog.pg_class limit 20;
insert into t1 select oid  from pg_catalog.pg_class limit 20;
insert into t2 select oid  from pg_catalog.pg_class limit 20;
insert into t2 select oid  from pg_catalog.pg_class limit 20;
create index idx_t1 on t1(id);
create index idx_t2 on t2(id);
analyze t1, t2;

select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename in ('t1', 't2')\gx
xman7=# select attname,null_frac,n_distinct,most_common_vals,most_common_freqs,correlation
 from pg_catalog.pg_stats where tablename in ('t1', 't2')\gx
-[ RECORD 1 ]-----+---------------------------------------------------------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | -0.5
most_common_vals  | {1247,2619,2830,2831,2832,2833,2836,2837,2840,4157,4158,4159,4160,4171,4172,6351,6352,16385,16399,16402}
most_common_freqs | {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
correlation       | 0.05403377
-[ RECORD 2 ]-----+---------------------------------------------------------------------------------------------------------
attname           | id
null_frac         | 0
n_distinct        | -0.5
most_common_vals  | {1247,2619,2830,2831,2832,2833,2836,2837,2840,4157,4158,4159,4160,4171,4172,6351,6352,16385,16399,16402}
most_common_freqs | {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
correlation       | 0.05403377

xman7=# 

select * from pg_catalog.pg_statistic where starelid in (select oid from pg_catalog.pg_class where relname in ('t1', 't2')) and staattnum = 1\gx
xman7=# select * from pg_catalog.pg_statistic where starelid in (select oid from pg_catalog.pg_class where relname in ('t1', 't2')) and staattnum = 1\gx
-[ RECORD 1 ]---------------------------------------------------------------------------------------------------------
starelid    | 16399
staattnum   | 1
stainherit  | f
stanullfrac | 0
stawidth    | 4
stadistinct | -0.5
stakind1    | 8
stakind2    | 3
stakind3    | 0
stakind4    | 0
stakind5    | 0
staop1      | 96
staop2      | 97
staop3      | 0
staop4      | 0
staop5      | 0
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
stanumbers2 | {0.05403377}
stanumbers3 | 
stanumbers4 | 
stanumbers5 | 
stavalues1  | {1247,2619,2830,2831,2832,2833,2836,2837,2840,4157,4158,4159,4160,4171,4172,6351,6352,16385,16399,16402}
stavalues2  | 
stavalues3  | 
stavalues4  | 
stavalues5  | 
-[ RECORD 2 ]---------------------------------------------------------------------------------------------------------
starelid    | 16402
staattnum   | 1
stainherit  | f
stanullfrac | 0
stawidth    | 4
stadistinct | -0.5
stakind1    | 8
stakind2    | 3
stakind3    | 0
stakind4    | 0
stakind5    | 0
staop1      | 96
staop2      | 97
staop3      | 0
staop4      | 0
staop5      | 0
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05,0.05}
stanumbers2 | {0.05403377}
stanumbers3 | 
stanumbers4 | 
stanumbers5 | 
stavalues1  | {1247,2619,2830,2831,2832,2833,2836,2837,2840,4157,4158,4159,4160,4171,4172,6351,6352,16385,16399,16402}
stavalues2  | 
stavalues3  | 
stavalues4  | 
stavalues5  | 

xman7=#


set enable_hashjoin=off;

explain select * from t1 , t2 where t1.id = t2.id;
xman7=# explain select * from t1 , t2 where t1.id = t2.id;
                          QUERY PLAN                           
---------------------------------------------------------------
 Merge Join  (cost=4.93..6.33 rows=80 width=8)
   Merge Cond: (t1.id = t2.id)
   ->  Sort  (cost=2.46..2.56 rows=40 width=4)
         Sort Key: t1.id
         ->  Seq Scan on t1  (cost=0.00..1.40 rows=40 width=4)
   ->  Sort  (cost=2.46..2.56 rows=40 width=4)
         Sort Key: t2.id
         ->  Seq Scan on t2  (cost=0.00..1.40 rows=40 width=4)
(8 rows)

xman7=# 

```debug
bt  
#0  get_variable_range (root=0x7fffecdb6178, vardata=0x7ffff3fa7d40, sortop=97, collation=0, min=0x7ffff3fa7d00, max=0x7ffff3fa7d08) at ../7_patch/src/backend/utils/adt/selfuncs.c:7541

p sslot.values[0]
$1 = 1247
p sslot.values[sslot.nvalues - 1]
$2 = 16402


验证80 rows 的SQL:
xman7=# select * from t1 , t2 where t1.id = t2.id;
  id   |  id   
-------+-------
  1247 |  1247
  1247 |  1247
  1247 |  1247
  1247 |  1247
  2619 |  2619
  2619 |  2619
  2619 |  2619
  2619 |  2619
  2830 |  2830
  2830 |  2830
  2830 |  2830
  2830 |  2830
  2831 |  2831
  2831 |  2831
  2831 |  2831
  2831 |  2831
  2832 |  2832
  2832 |  2832
  2832 |  2832
  2832 |  2832
  2833 |  2833
  2833 |  2833
  2833 |  2833
  2833 |  2833
  2836 |  2836
  2836 |  2836
  2836 |  2836
  2836 |  2836
  2837 |  2837
  2837 |  2837
  2837 |  2837
  2837 |  2837
  2840 |  2840
  2840 |  2840
  2840 |  2840
  2840 |  2840
  4157 |  4157
  4157 |  4157
  4157 |  4157
  4157 |  4157
  4158 |  4158
  4158 |  4158
  4158 |  4158
  4158 |  4158
  4159 |  4159
  4159 |  4159
  4159 |  4159
  4159 |  4159
  4160 |  4160
  4160 |  4160
  4160 |  4160
  4160 |  4160
  4171 |  4171
  4171 |  4171
  4171 |  4171
  4171 |  4171
  4172 |  4172
  4172 |  4172
  4172 |  4172
  4172 |  4172
  6351 |  6351
  6351 |  6351
  6351 |  6351
  6351 |  6351
  6352 |  6352
  6352 |  6352
  6352 |  6352
  6352 |  6352
 16385 | 16385
 16385 | 16385
 16385 | 16385
 16385 | 16385
 16399 | 16399
 16399 | 16399
 16399 | 16399
 16399 | 16399
 16402 | 16402
 16402 | 16402
 16402 | 16402
 16402 | 16402
(80 rows)

xman7=# 

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com



Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi, hackers

Optimize MCV statistics for sortable types

Preserve MCV values in ascending order for sort-comparable data types
by introducing a new statistic kind, STATISTIC_KIND_MCV_VALUE_SORTED.
This allows planner code to exploit the ordering of MCV values instead
of repeatedly comparing every MCV entry with a constant.

In compute_scalar_stats(), retain the existing MCV generation logic and
use an additional ScalarMCVItem workspace to produce the value-sorted
MCV list. For sortable types, the sorted MCV list can replace the
legacy STATISTIC_KIND_MCV entry, so no additional statistics slot is
required.

Use the sorted MCV values during selectivity estimation and range
detection. The optimizations are applied conservatively, with strict
conditions on the statistics kind, data type, collation, and operator
ordering compatibility:

* In var_eq_const(), use the minimum and maximum MCV values to quickly
  determine whether the constant can match an MCV entry, and use binary
  search when the constant falls within the MCV range.
* In mcv_selectivity(), use the sorted MCV values to find the range of
  entries satisfying <, <=, >, or >=, avoiding per-entry operator
  evaluation.
* In get_stats_slot_range(), use the first and last values of a sorted
  MCV list directly when its ordering is compatible with the requested
  sort operator, avoiding the O(N) scan otherwise required to determine
  the minimum and maximum values.

When the conditions for these optimizations are not satisfied, retain
the existing behavior.

The optimization reduces the number of expensive MCV comparisons while
preserving the existing behavior for non-sortable types and statistics
without a compatible ordering.

Update the pg_stats view to expose STATISTIC_KIND_MCV_VALUE_SORTED through
most_common_vals and most_common_freqs.

Changes from v4:
1. Fixed compute_scalar_stats() to adjust the MCV list members according
   to the result returned by analyze_mcv_list().

2. Fixed an issue in mergejoinscansel() -> get_variable_range(), where
   the minimum and maximum values could be overwritten incorrectly.
   Instead, get_stats_slot_range() now leverages the ordering property
   of MCV values to compare and determine the minimum and maximum values.

3. The optimization for eqjoinsel_find_matches() in the following call
   paths is not included in this patch due to its complexity and remains
   as future work:
       eqjoinsel() -> eqjoinsel_inner() -> eqjoinsel_find_matches()
       eqjoinsel() -> eqjoinsel_semi()  -> eqjoinsel_find_matches()

attached:
01-test_setup_for_var_eq_const(),mcv_selectivity().sql
01-test_result_for_var_eq_const(),mcv_selectivity().xlsx

02-get_variable_range()-setup_and_result.sql

03-eqjoinsel()_setup_text.sql


Today is the Mid-Autumn Festival in China. 
Wish everyone a happy Mid-Autumn Festival, with a full moon, happiness,
and wonderful moments with family and friends.

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi hackers,

Based on v5, I made the following changes in v6:
0. compute_scalar_stats(): Use a lightweight algorithm to generate MCVs with values[] sorted.
1. In mcv_selectivity(), use get_ordering_op_properties(operatoroid) to obtain the CompareType for the operator.
2. Simplify the non-hash path in eqjoinsel_find_matches().
The new implementation only handles the !op_is_reversed case, and only when sslot2 uses
MCV_SPECIAL_COMPARE_THRESHOLD. When op_is_reversed is true, the matching logic becomes considerably
more complicated. For sslot2 with MCV_SPECIAL_COMPARE_THRESHOLD, we can use the min/max values and
binary search to find the matching range.


The conditions for enabling the new logic are currently intentionally quite strict and conservative, 
as described in the commit message:
> Use the sorted MCV values during selectivity estimation and range
> detection. The optimizations are applied conservatively, with strict
> conditions on the statistics kind, collation, data type, and operator
> ordering compatibility.

I have verified the functional correctness of v6 and debugged the implementation.
I also compared the patched version with an unpatched version. The query plans and 
row-count estimates I observed were consistent between the two versions.

In addition, after initdb, I ran the following query on both versions:
sql
select schemaname,tablename,attname,attnum,inherited,null_frac,avg_width,
       n_distinct,most_common_vals,most_common_freqs,histogram_bounds,correlation,
       most_common_elems,most_common_elem_freqs,elem_count_histogram,
       range_length_histogram,range_empty_frac,range_bounds_histogram
from pg_catalog.pg_stats
order by 1,2,3,4,5,6
\gx


The difference I observed was the ordering of the elements in most_common_vals and most_common_freqs.
Before the patch, they were ordered by most_common_freqs in descending order. With the patch, they are 
ordered by most_common_vals in ascending order.
There is one issue that I have not figured out yet.
When accessing the underlying catalog table directly, running the query interactively in psql xman7 displays 
he values of most_common_vals and most_common_freqs correctly.
However, when I run the same SQL through:
sh
cat xxxx.sql | psql xman7
the values of these two columns are not displayed.

I am not sure yet whether this is related to the patch or to how psql handles the output in this case.
Any suggestions on where I should look would be appreciated.

The SQL is as follows:
select * from (
  SELECT n.nspname AS schemaname,
     c.relname AS tablename,
     a.attname,
     a.attnum,
     s.stainherit AS inherited,
     s.stanullfrac AS null_frac,
     s.stadistinct AS n_distinct,
     CASE
             WHEN s.stakind1 = 1 THEN 1
             WHEN s.stakind2 = 1 THEN 1
             WHEN s.stakind3 = 1 THEN 1
             WHEN s.stakind4 = 1 THEN 1
             WHEN s.stakind5 = 1 THEN 1
             WHEN s.stakind1 = 8 THEN 8
             WHEN s.stakind2 = 8 THEN 8
             WHEN s.stakind3 = 8 THEN 8
             WHEN s.stakind4 = 8 THEN 8
             WHEN s.stakind5 = 8 THEN 8
             ELSE 0
         END AS KIND_MCV,
         CASE
             WHEN s.stakind1 = 1 THEN s.stavalues1
             WHEN s.stakind2 = 1 THEN s.stavalues2
             WHEN s.stakind3 = 1 THEN s.stavalues3
             WHEN s.stakind4 = 1 THEN s.stavalues4
             WHEN s.stakind5 = 1 THEN s.stavalues5
             ELSE NULL::anyarray
         END AS most_common_vals,
         CASE
             WHEN s.stakind1 = 1 THEN s.stanumbers1
             WHEN s.stakind2 = 1 THEN s.stanumbers2
             WHEN s.stakind3 = 1 THEN s.stanumbers3
             WHEN s.stakind4 = 1 THEN s.stanumbers4
             WHEN s.stakind5 = 1 THEN s.stanumbers5
             ELSE NULL::real[]
         END AS most_common_freqs,
         CASE
             WHEN s.stakind1 = 2 THEN s.stavalues1
             WHEN s.stakind2 = 2 THEN s.stavalues2
             WHEN s.stakind3 = 2 THEN s.stavalues3
             WHEN s.stakind4 = 2 THEN s.stavalues4
             WHEN s.stakind5 = 2 THEN s.stavalues5
             ELSE NULL::anyarray
         END AS histogram_bounds,
         CASE
             WHEN s.stakind1 = 3 THEN s.stanumbers1[1]
             WHEN s.stakind2 = 3 THEN s.stanumbers2[1]
             WHEN s.stakind3 = 3 THEN s.stanumbers3[1]
             WHEN s.stakind4 = 3 THEN s.stanumbers4[1]
             WHEN s.stakind5 = 3 THEN s.stanumbers5[1]
             ELSE NULL::real
         END AS correlation,
         CASE
             WHEN s.stakind1 = 4 THEN s.stavalues1
             WHEN s.stakind2 = 4 THEN s.stavalues2
             WHEN s.stakind3 = 4 THEN s.stavalues3
             WHEN s.stakind4 = 4 THEN s.stavalues4
             WHEN s.stakind5 = 4 THEN s.stavalues5
             ELSE NULL::anyarray
         END AS most_common_elems,
         CASE
             WHEN s.stakind1 = 4 THEN s.stanumbers1
             WHEN s.stakind2 = 4 THEN s.stanumbers2
             WHEN s.stakind3 = 4 THEN s.stanumbers3
             WHEN s.stakind4 = 4 THEN s.stanumbers4
             WHEN s.stakind5 = 4 THEN s.stanumbers5
             ELSE NULL::real[]
         END AS most_common_elem_freqs,
         CASE
             WHEN s.stakind1 = 5 THEN s.stanumbers1
             WHEN s.stakind2 = 5 THEN s.stanumbers2
             WHEN s.stakind3 = 5 THEN s.stanumbers3
             WHEN s.stakind4 = 5 THEN s.stanumbers4
             WHEN s.stakind5 = 5 THEN s.stanumbers5
             ELSE NULL::real[]
         END AS elem_count_histogram,
         CASE
             WHEN s.stakind1 = 6 THEN s.stavalues1
             WHEN s.stakind2 = 6 THEN s.stavalues2
             WHEN s.stakind3 = 6 THEN s.stavalues3
             WHEN s.stakind4 = 6 THEN s.stavalues4
             WHEN s.stakind5 = 6 THEN s.stavalues5
             ELSE NULL::anyarray
         END AS range_length_histogram,
         CASE
             WHEN s.stakind1 = 6 THEN s.stanumbers1[1]
             WHEN s.stakind2 = 6 THEN s.stanumbers2[1]
             WHEN s.stakind3 = 6 THEN s.stanumbers3[1]
             WHEN s.stakind4 = 6 THEN s.stanumbers4[1]
             WHEN s.stakind5 = 6 THEN s.stanumbers5[1]
             ELSE NULL::real
         END AS range_empty_frac,
         CASE
             WHEN s.stakind1 = 7 THEN s.stavalues1
             WHEN s.stakind2 = 7 THEN s.stavalues2
             WHEN s.stakind3 = 7 THEN s.stavalues3
             WHEN s.stakind4 = 7 THEN s.stavalues4
             WHEN s.stakind5 = 7 THEN s.stavalues5
             ELSE NULL::anyarray
         END AS range_bounds_histogram
    FROM pg_statistic s
      JOIN pg_class c ON c.oid = s.starelid
      JOIN pg_attribute a ON c.oid = a.attrelid AND a.attnum = s.staattnum
      LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
   WHERE NOT a.attisdropped AND has_column_privilege(c.oid, a.attnum, 'select'::text) AND (c.relrowsecurity = false OR NOT row_security_active(c.oid))
   ) as t1 order by 1,2,3,4,5,6;



I have also attached a test SQL file covering the main functions involved in this change,
 including var_eq_const(), mcv_selectivity(), get_stats_slot_range(), and eqjoinsel_find_matches(), 
so that others can easily reproduce and test the relevant cases.


For convenience, I also list below the modified files and functions. This should make it easier to get 
an overview of the changes and review the relevant code.

### Modified files and functions
src/include/catalog/pg_statistic.h
    #define STATISTIC_KIND_MCV_VALUE_SORTED 8
    - Adds a new statistics kind for MCV values sorted by value.

src/backend/commands/analyze.c
     - compute_scalar_stats() Generates STATISTIC_KIND_MCV_VALUE_SORTED

src/backend/catalog/system_views.sql
    - Adds support for displaying STATISTIC_KIND_MCV_VALUE_SORTED statistics.

src/include/utils/lsyscache.h
src/backend/utils/cache/lsyscache.c
    - Adds the get_attstatsslot_mcv() helper, similar to get_attstatsslot(), for retrieving both
       STATISTIC_KIND_MCV_VALUE_SORTED and STATISTIC_KIND_MCV statistics.

src/include/statistics/stat_utils.h
src/backend/statistics/stat_utils.c
    -Adds the following helper functions:
        - get_max_mcv_frequency()   Gets the maximum frequency among the MCV entries.
        - get_min_mcv_frequency()    Gets the minimum frequency among the MCV entries.

src/backend/executor/nodeHash.c
    - Uses get_attstatsslot_mcv() to retrieve MCV statistics.

src/backend/utils/adt/like_support.c
      - prefix_selectivity()  Uses var_eq_const() for eq_sel.
      - patternsel_common() 
            - Uses var_eq_const().
            - Uses mcv_selectivity(..., oprid) for MCV selectivity.

src/backend/utils/adt/network_selfuncs.c
      - networksel()   Uses mcv_selectivity(..., operator).
      - networkjoinsel_inner() Uses get_attstatsslot_mcv().

src/include/utils/selfuncs.h
src/backend/utils/adt/selfuncs.c
***This is the main file affected by the patch. The major changes include:***
var_eq_const() ***
var_eq_non_const()  
      - Uses get_attstatsslot_mcv() and get_max_mcv_frequency().
scalarineqsel()
      - Uses mcv_selectivity().
mcv_selectivity()***
generic_restriction_selectivity()
      - Uses mcv_selectivity().  
ineq_histogram_selectivity()
      - Uses get_attstatsslot_mcv().
booltestsel()  
      - Uses get_attstatsslot_mcv().
neqjoinsel()  
      - Uses eqjoinsel().
eqjoinsel() ***
eqjoinsel_inner()   
       - Uses eqjoinsel_find_matches().
eqjoinsel_semi()   
      - Uses eqjoinsel_find_matches().
eqjoinsel_find_matches() ***
estimate_hash_bucket_stats()  
      - Uses get_attstatsslot_mcv() and get_max_mcv_frequency().
get_variable_range()   
      - Uses get_stats_slot_range() and get_attstatsslot_mcv().
get_stats_slot_range() ***
mergejoinscansel() 
       - Uses get_variable_range(), which in turn uses mcv_selectivity().

The functions marked above are also the main entry points where the new sorted-MCV 
information is consumed during selectivity estimation and range detection.


As a next step, I plan to run some additional performance tests using EXPLAIN to better understand 
the impact of the changes on query planning and selectivity estimation.

I would greatly appreciate any comments or suggestions from the community. In particular, feedback
on the implementation, the conservative conditions for applying the optimization, and any potential 
performance concerns would be very helpful.

Thanks for your time and review.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi,

1. Update the pg_stats_ext_exprs view to expose STATISTIC_KIND_MCV_VALUE_SORTED
through most_common_vals and most_common_freqs.

2. Regarding pg_statistic_get_difference():

The input statistics can come either from pg_stats or directly from the user. 
I initially considered improving the detection of the stat kind during import, 
but there are several considerations and implementation difficulties. 
For now, I think it is better to keep the existing logic.

* Adding a stat kind parameter would rely on the caller to make the correct decision, 
     and would also affect quite a few interfaces.
* Another idea is to inspect most_common_vals and most_common_freqs during import, 
sort them if possible, and generate STATISTIC_KIND_MCV_VALUE_SORTED; otherwise, 
keep STATISTIC_KIND_MCV.

I looked into the latter, but it seems more complicated than expected because both inputs are text. 
We would need to deserialize them into the actual data type, sort them, and serialize them again. 
I have not worked out the details yet. If anyone is familiar with this part of the code and has suggestions, 
I would be happy to investigate further.

3. I think pg_statistic_get_difference() could also have stronger validation in the future.

For input from pg_stats, the core code has already processed the statistics, so for STATISTIC_KIND_MCV, 
most_common_freqs[0] is the maximum and most_common_freqs[n - 1] is the minimum.

For user-provided input, however, there is currently no such restriction. We only perform basic checks, 
such as array lengths and NULLs. We could consider strengthening these checks in the future.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
I write:
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-09-30 21:34
>To: pgsql-hackers 
>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>
>Hi,
>
>1. Update the pg_stats_ext_exprs view to expose STATISTIC_KIND_MCV_VALUE_SORTED
>through most_common_vals and most_common_freqs.
>
>2. Regarding pg_statistic_get_difference():
>
>The input statistics can come either from pg_stats or directly from the user. 
>I initially considered improving the detection of the stat kind during import, 
>but there are several considerations and implementation difficulties. 
>For now, I think it is better to keep the existing logic.
>
>* Adding a stat kind parameter would rely on the caller to make the correct decision, 
>     and would also affect quite a few interfaces.
>* Another idea is to inspect most_common_vals and most_common_freqs during import, 
>sort them if possible, and generate STATISTIC_KIND_MCV_VALUE_SORTED; otherwise, 
>keep STATISTIC_KIND_MCV.
>
>I looked into the latter, but it seems more complicated than expected because both inputs are text. 
>We would need to deserialize them into the actual data type, sort them, and serialize them again. 
>I have not worked out the details yet. If anyone is familiar with this part of the code and has suggestions, 
>I would be happy to investigate further.
>
>3. I think pg_statistic_get_difference() could also have stronger validation in the future.
>
>For input from pg_stats, the core code has already processed the statistics, so for STATISTIC_KIND_MCV, 
>most_common_freqs[0] is the maximum and most_common_freqs[n - 1] is the minimum.
>
>For user-provided input, however, there is currently no such restriction. We only perform basic checks, 
>such as array lengths and NULLs. We could consider strengthening these checks in the future.

Sorry, there was a mistake in my previous message. 
The function I meant was pg_restore_attribute_stats(), not pg_statistic_get_difference().

pg_restore_extended_stats() has the same issue: 
it always uses STATISTIC_KIND_MCV and does not check whether most_common_freqs[0] is the maximum frequency 
and most_common_freqs[n - 1] is the minimum frequency.

One possible solution is to add an optional mcv_kind parameter to these two functions, 
with the default value being STATISTIC_KIND_MCV.

This allows existing callers to keep the current behavior, while callers that provide
STATISTIC_KIND_MCV_VALUE_SORTED statistics can explicitly preserve the correct statistics kind.

This should minimize the impact on existing interfaces. Comments and suggestions are welcome.



regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
I write:
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-10-01 10:21
>To: pgsql-hackers 
>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>....
>Sorry, there was a mistake in my previous message. 
>The function I meant was pg_restore_attribute_stats(), not pg_statistic_get_difference().
>
>pg_restore_extended_stats() has the same issue: 
>it always uses STATISTIC_KIND_MCV and does not check whether most_common_freqs[0] is the maximum frequency 
>and most_common_freqs[n - 1] is the minimum frequency.
>
>One possible solution is to add an optional mcv_kind parameter to these two functions, 
>with the default value being STATISTIC_KIND_MCV.
>
>This allows existing callers to keep the current behavior, while callers that provide
>STATISTIC_KIND_MCV_VALUE_SORTED statistics can explicitly preserve the correct statistics kind.
>
>This should minimize the impact on existing interfaces. Comments and suggestions are welcome.

Hi,

    Add an optional most_common_vals_kind parameter to pg_restore_attribute_stats() 
and the expr arguments of pg_restore_extended_stats() to specify whether most_common_vals[]
and most_common_freqs[] are of type 1-STATISTIC_KIND_MCV or 8-STATISTIC_KIND_MCV_VALUE_SORTED.

If the parameter is not specified, it defaults to 1-STATISTIC_KIND_MCV, preserving the existing behavior.

The corresponding test SQL and test results are attached.

regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
    Rebase.
regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
              Rebase.

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi,
   
    Previous versions also modified import_fetched_statistics()->import_attribute_statistics() 
by adding the most_common_vals_kind parameter. 

   However, when analyzing a PostgreSQL FDW, for example with ANALYZE simport_ftable; 
in contrib/postgres_fdw/sql/postgres_fdw.sql, fetch_attstats() did not retrieve the
corresponding MCV kind to pass to the newly added most_common_vals_kind parameter. 
This issue is now fixed.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi,

I made the following changes:
  - Simplified stats_import.sql by using the check_sql helper to execute the queries and verify the results.
     This significantly reduces the duplicated content between stats_import.sql and stats_import.out.
  - I also modified the query used for checking imported statistics to avoid outputting environment-dependent fields, 
     such as tableid, statistics_id, and statistics_owner. These fields are not essential for the regression test and could
     cause unnecessary differences across environments.

  - Added test cases in collate.icu.utf8.sql and corresponding expected output in collate.icu.utf8.out to verify whether
      scanning the entire MCV array is needed.

Thanks for the review.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi,

In v12, the CF tests showed failures in the following two TAP tests:
  271/429 postgresql:scripts / scripts/102_vacuumdb_stages  ERROR  6.22s exit status 2
  272/429 postgresql:scripts / scripts/100_vacuumdb               ERROR 10.90s exit status 2

It was also able to reproduce the issue manually with the following commands:
SELECT pg_catalog.set_config('search_path', '', false);
SET default_statistics_target=10;
RESET vacuum_cost_delay;
ANALYZE pg_catalog.pg_proc;

The issue was caused by the MCV tracking logic. The fix is to remove the rightmost entry
with the smallest count and shift the following elements when the number of tracked
values reaches num_mcv, making room for the new value at the end:
/*
 * If track_cnt reaches num_mcv, remove the rightmost
 * entry with the smallest count and shift the
 * following elements to the left, making room for the
 * new value at the end.
 */

After applying this fix, the three related test cases pass successfully in my environment.

Thanks again.


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi
    Fixed the cpluspluscheck failure by renaming the operator parameter to oproid in mcv_selectivity().
regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Subject: ANALYZE correctness and performance testing

Hi hackers,

The patch is now reaching a relatively complete stage, and all CFBot tests are passing. 
I am now starting to evaluate its correctness and performance more systematically.

As the first step, I focused on the ANALYZE side, particularly on the correctness of
generating value-sorted MCV statistics and the performance overhead of collecting them.

For the test, I created a table with 100,020 rows and set the statistics target to 10,000. 
Most values occur 10 times, while three values have slightly higher frequencies. 

The resulting MCV statistics show the expected difference between v14 and the current master.
With v14, where STATISTIC_KIND_MCV_VALUE_SORTED is used, the MCV values are sorted by value:
             mcv_type              | no |      value       |  frequency  
-----------------------------------+----+------------------+-------------
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  1 | "PostgreSQL 001" | 0.10002
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  2 | "PostgreSQL 002" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  3 | "PostgreSQL 003" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  4 | "PostgreSQL 004" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  5 | "PostgreSQL 005" | 0.10003999
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  6 | "PostgreSQL 006" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  7 | "PostgreSQL 007" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  8 | "PostgreSQL 008" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED |  9 | "PostgreSQL 009" | 0.099980004
 8-STATISTIC_KIND_MCV_VALUE_SORTED | 10 | "PostgreSQL 010" | 0.10007998
(10 rows)

In contrast, on master, the MCVs are sorted by frequency:
       mcv_type       | no |      value       |  frequency  
----------------------+----+------------------+-------------
 1-STATISTIC_KIND_MCV |  1 | "PostgreSQL 010" | 0.10007998
 1-STATISTIC_KIND_MCV |  2 | "PostgreSQL 005" | 0.10003999
 1-STATISTIC_KIND_MCV |  3 | "PostgreSQL 001" | 0.10002
 1-STATISTIC_KIND_MCV |  4 | "PostgreSQL 002" | 0.099980004
 1-STATISTIC_KIND_MCV |  5 | "PostgreSQL 003" | 0.099980004
 1-STATISTIC_KIND_MCV |  6 | "PostgreSQL 004" | 0.099980004
 1-STATISTIC_KIND_MCV |  7 | "PostgreSQL 006" | 0.099980004
 1-STATISTIC_KIND_MCV |  8 | "PostgreSQL 007" | 0.099980004
 1-STATISTIC_KIND_MCV |  9 | "PostgreSQL 008" | 0.099980004
 1-STATISTIC_KIND_MCV | 10 | "PostgreSQL 009" | 0.099980004
(10 rows)

This is also consistent with the intended design: the new statistic kind keeps the
MCV values sorted by value while preserving the corresponding frequencies.

For the ANALYZE performance, I ran 100 consecutive ANALYZE operations in each case.
The total time was:
              1st                2nd             3rd               4th               avg
================================================================
v14:       22510.146  23805.940  24146.746  24869.801  23833.158
master:  22407.108  23095.573  24068.918  23933.353  23376.238
This corresponds to approximately:
v14:       238.33 ms / ANALYZE
master:  233.76 ms / ANALYZE

So, for this particular test case, the additional cost is about 1.95% per ANALYZE.

I would appreciate any feedback on whether this is a reasonable way to evaluate the
ANALYZE-side overhead, and whether there are other representative workloads or
cases that would be useful to test.

In particular, comments from people familiar with analyze.c, MCV generation, or statistics
collection would be very helpful. I'm also interested in whether the current implementation
introduces any unnecessary work that could be optimized further.
As the next step, I plan to measure the performance impact on the different consumers of
these statistics, including the relevant equality/range comparison and join selectivity estimation paths.

Thanks in advance for any review and suggestions.


The test SQL and the corresponding results are as follows:
---------------------
DROP TABLE IF EXISTS t_sort_mcv_100;
CREATE TABLE t_sort_mcv_100(name text);
ALTER TABLE t_sort_mcv_100 ALTER COLUMN name SET STATISTICS 10000;

select attname,attstattarget from pg_catalog.pg_attribute where attrelid = 't_sort_mcv_100'::regclass and attnum = 1;

DO $$
DECLARE i int := 0;
BEGIN
    LOOP
        EXIT WHEN i >= 10000;
        i := i + 1;
        INSERT INTO t_sort_mcv_100 SELECT repeat( 'PostgreSQL', 1) || to_char(g, '099') FROM generate_series(1, 10) g;
    END LOOP;
END $$;

INSERT INTO t_sort_mcv_100 SELECT repeat( 'PostgreSQL', 1) || ' 010' FROM generate_series(1, 10) g;
INSERT INTO t_sort_mcv_100 SELECT repeat( 'PostgreSQL', 1) || ' 005' FROM generate_series(1,  6) g;
INSERT INTO t_sort_mcv_100 SELECT repeat( 'PostgreSQL', 1) || ' 001' FROM generate_series(1,  4) g;

select count(*) from t_sort_mcv_100;

---------------------
\timing on

DO $$
DECLARE i int := 0;
BEGIN
    LOOP
        EXIT WHEN i >= 100;
        i := i + 1;
        ANALYZE t_sort_mcv_100;
    END LOOP;
END $$;

---------------------
WITH s AS (SELECT stakind1,stanumbers1, stavalues1::text AS values_text
 FROM pg_catalog.pg_statistic
 WHERE starelid = 't_sort_mcv_100'::regclass AND staattnum = 1
),
v AS ( SELECT ordinality AS n, value
 FROM s, LATERAL unnest( string_to_array(trim(both '{}' FROM values_text), ',' ) ) 
 WITH ORDINALITY AS u(value, ordinality)
),
f AS ( SELECT ordinality AS n, frequency
 FROM s, LATERAL unnest(stanumbers1) 
 WITH ORDINALITY AS u(frequency, ordinality)
)
SELECT CASE 
  when s.stakind1 = 1 then '1-STATISTIC_KIND_MCV' 
  when s.stakind1 = 8 then '8-STATISTIC_KIND_MCV_VALUE_SORTED' 
  else NULL END AS MCV_TYPE
	,v.n as no, v.value, f.frequency
 FROM v JOIN f USING(n) JOiN s ON 1=1
 ORDER BY v.n;


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi,

I have found that adding C code to measure the execution time of the specific functions
being modified provides a more reliable way to assess their performance than measuring
the execution time of SQL commands.

The execution time of each modified function is relatively small, and measuring it indirectly
through SQL commands introduces noise from other functions and operations involved in
executing those commands. This makes it difficult to isolate the performance impact of our
changes. I also ran each test more than 100 times to obtain more consistent and reliable results.

As a first step, I added C code to three functions to make their individual performance impacts more observable:
- compute_scalar_stats(): generates STATISTIC_KIND_MCV_VALUE_SORTED (kind 8) for sortable data types.
- var_eq_const(): handles =.
- mcv_selectivity(): handles >, >=, <, and <=.

Based on the test results:
- compute_scalar_stats(): 
The patch version is, on average, ***3.2%*** slower than master. This result surprised me, since the patch does not
introduce any expensive sorting or value-comparison operations in this function. I would have expected the
performance impact to be negligible, so I am still investigating the cause.
- var_eq_const(): The patch version is, on average, ***42.19%*** faster than master. This result was quite surprising
and encouraging.
- mcv_selectivity(): The patch version is, on average, ***20.62%*** faster than master. This result was also encouraging,
although the improvement is smaller than that for var_eq_const(). On closer inspection, I found that <= and >= fall back
to the original full MCV scan because get_ordering_op_properties() does not provide the comparison strategy for these
operators in the tested cases. Consequently, their performance is almost unchanged compared with master. I am still
investigating how best to address this.

For reference, I have attached the v14.patch.debug patch, along with the relevant test scripts and test results. 
The patch is based on v14 and adds function-level performance reporting.

The test files are organized as follows:
- 00-setup.sql: test setup.
- 01-gen_test_sql_sh: generates the SQL files used for testing.

**For comparing estimated row counts in execution plans:**
- 02-gen_master_explain_var_eq_cosnt_mcv_selectivity_sh
- 03-gen_patch_explain_var_eq_cosnt_mcv_selectivity_sh
- 06-compare_patch_explain_var_eq_cosnt_mcv_selectivity_sh

**For performance testing:**
- compute_scalar_stats():
  cat compute_scalar_stats.sql | psql xman7 | grep -v ANALYZE
- var_eq_const() and mcv_selectivity():
  - 04-test_master_var_eq_cosnt_mcv_selectivity_sh
  - 05-test_patch_var_eq_cosnt_mcv_selectivity_sh

The aggregated ANALYZE test results are also included in test_result_analyze.xlsx.

I would appreciate any feedback on the testing methodology and the results, particularly on
the unexpected overhead in compute_scalar_stats() and possible ways to improve the handling 
f <= and >= in mcv_selectivity().

Thanks for your time and any suggestions.


regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
I write
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-10-17 12:18
>To: pgsql-hackers 
>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>
>Hi,
>
>I have found that adding C code to measure the execution time of the specific functions
>being modified provides a more reliable way to assess their performance than measuring
>the execution time of SQL commands.
>
>The execution time of each modified function is relatively small, and measuring it indirectly
>through SQL commands introduces noise from other functions and operations involved in
>executing those commands. This makes it difficult to isolate the performance impact of our
>changes. I also ran each test more than 100 times to obtain more consistent and reliable results.
>
>As a first step, I added C code to three functions to make their individual performance impacts more observable:
>- compute_scalar_stats(): generates STATISTIC_KIND_MCV_VALUE_SORTED (kind 8) for sortable data types.
>- var_eq_const(): handles =.
>- mcv_selectivity(): handles >, >=, <, and <=.
>
>Based on the test results:
>- compute_scalar_stats(): 
>The patch version is, on average, ***3.2%*** slower than master. This result surprised me, since the patch does not
>introduce any expensive sorting or value-comparison operations in this function. I would have expected the
>performance impact to be negligible, so I am still investigating the cause.
>- var_eq_const(): The patch version is, on average, ***42.19%*** faster than master. This result was quite surprising
>and encouraging.
>- mcv_selectivity(): The patch version is, on average, ***20.62%*** faster than master. This result was also encouraging,
>although the improvement is smaller than that for var_eq_const(). On closer inspection, I found that <= and >= fall back
>to the original full MCV scan because get_ordering_op_properties() does not provide the comparison strategy for these
>operators in the tested cases. Consequently, their performance is almost unchanged compared with master. I am still
>investigating how best to address this.


Hi,

I have replaced get_ordering_op_properties() with get_oprrest(), as used in V5. 
The latter is already used by scalararraysel() in the same file.

The following restriction estimator functions are defined in fmgroids.h:
#define F_SCALARLTSEL   103
#define F_SCALARGTSEL  104
#define F_SCALARLESEL   336
#define F_SCALARGESEL  337

In src/backend/utils/adt/selfuncs.c, the relevant call chain is as follows:

scalarltsel()    -- Selectivity of "<" for scalars.
scalarlesel()   -- Selectivity of "<=" for scalars.
scalargtsel()  -- Selectivity of ">" for scalars.
scalargesel()  -- Selectivity of ">=" for scalars.
    --> scalarineqsel_wrapper(PG_FUNCTION_ARGS, bool isgt, bool iseq)
        --> scalarineqsel()  -- Selectivity of "<", "<=", ">", and ">=" for scalars.
            --> mcv_selectivity()

After switching to get_oprrest(), I reran the performance tests for var_eq_const() and mcv_selectivity()
to compare the patch against master.

The results are as follows:
  - var_eq_const():     The patch version is, on average, ***43.88% faster*** than master.
  - mcv_selectivity(): The patch version is, on average, ***39.02% faster*** than master.

Based on the test results:
In master, the execution times of var_eq_const() and mcv_selectivity() are both relatively stable at around 0.080 ms.
With the patch, the execution times are generally around 0.040–0.050 ms for both functions.

Please see the attached XLS file for the detailed test results and analysis.
 
>For reference, I have attached the v14.patch.debug patch, along with the relevant test scripts and test results. 
>The patch is based on v14 and adds function-level performance reporting.
>
>The test files are organized as follows:
>- 00-setup.sql: test setup.
>- 01-gen_test_sql_sh: generates the SQL files used for testing.
>
>**For comparing estimated row counts in execution plans:**
>- 02-gen_master_explain_var_eq_cosnt_mcv_selectivity_sh
>- 03-gen_patch_explain_var_eq_cosnt_mcv_selectivity_sh
>- 06-compare_patch_explain_var_eq_cosnt_mcv_selectivity_sh
>
>**For performance testing:**
>- compute_scalar_stats():
>  cat compute_scalar_stats.sql | psql xman7 | grep -v ANALYZE
>- var_eq_const() and mcv_selectivity():
>  - 04-test_master_var_eq_cosnt_mcv_selectivity_sh
>  - 05-test_patch_var_eq_cosnt_mcv_selectivity_sh
>
>The aggregated ANALYZE test results are also included in test_result_analyze.xlsx.
>
>I would appreciate any feedback on the testing methodology and the results, particularly on
>the unexpected overhead in compute_scalar_stats() and possible ways to improve the handling 
>f <= and >= in mcv_selectivity().
>
>Thanks for your time and any suggestions.

	
ZizhuanLiu X-MAN
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
I write:
>Original
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-10-17 20:06
>To: pgsql-hackers 
>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>......
>The results are as follows:
>  - var_eq_const():    The patch version is, on average, 43.88% faster than master.
>  - mcv_selectivity(): The patch version is, on average, 39.02% faster than master.
>......


Hi,

Using the same testing methodology, I also tested eqjoinsel(), mergejoinscansel(), and EXPLAIN planning time.

The results are summarized below.
- Execution plans: Master and the patch produce identical plans for the tested SQL cases.
   See the 02-stats_data_explain sheet in the attached XLS file.
- Performance: The patch shows substantial improvements in both eqjoinsel() and mergejoinscansel(),
   as well as in planning time. See the 03-Raw_test_data_analyze and 03-test_data_analyze_2 sheets.

Some measurements for master were anomalous. To make the comparison fairer, 03-test_data_analyze_2 excludes
those anomalous master measurements and recalculates the results using the remaining measurements and the
same methodology for both master and the patch. The results from both data sets are shown below.

Metric                                03-Raw_test_data_analyze      03-test_data_analyze_2
eqjoinsel()                         96.46%                                      95.08%
mergejoinscansel()           80.23%                                      74.17%
EXPLAIN planning time   91.90%                                      89.05%

These results mark an important milestone in my testing. Based on the current test cases, 
the SQL scenarios, relevant functions, and observed performance improvements are summarized below.

1. Scalar equality
- sql
     SELECT  FROM t WHERE col1 = const;
- Function: var_eq_const()
- Average performance improvement: 43.88%

2. Scalar inequality comparisons
- sql
     SELECT  FROM t WHERE col1 <   const;
     SELECT  FROM t WHERE col1 <= const;
     SELECT  FROM t WHERE col1 >   const;
     SELECT  FROM t WHERE col1 >= const;
- Function: mcv_selectivity()
- Average performance improvement: 39.02%

3. Join-related queries
- sql
     SELECT  FROM t1 WHERE col1 IN (SELECT col2 FROM t2);
     SELECT  FROM t1, t2 WHERE t1.col1 = t2.col2;
- eqjoinsel(): average performance improvement of 95.08%
- mergejoinscansel(): average performance improvement of 74.17%
- EXPLAIN planning time: average improvement of 89.05%

These results are encouraging, although the current SQL scenarios may not cover all relevant workloads. 
The patch could also affect other planning scenarios, and I would particularly appreciate feedback on
cases that might regress or show substantially different performance.

I would be grateful for any feedback on the test coverage, the interpretation of these results, or additional
scenarios that would be useful to test. If anyone has observed regressions or has suggestions for improving
the implementation, I would welcome the opportunity to investigate them.

Thank you for your time and feedback.


The following scripts were used to run the tests:
DROP TABLE IF EXISTS t_eqjoinsel_mergejoinscansel_1;
CREATE TABLE t_eqjoinsel_mergejoinscansel_1(name text COLLATE case_insensitive);
ALTER TABLE t_eqjoinsel_mergejoinscansel_1 ALTER COLUMN name SET STATISTICS 10000;

DROP TABLE IF EXISTS t_eqjoinsel_mergejoinscansel_2;
CREATE TABLE t_eqjoinsel_mergejoinscansel_2(name text COLLATE case_insensitive);
ALTER TABLE t_eqjoinsel_mergejoinscansel_2 ALTER COLUMN name SET STATISTICS 10000;

select attrelid,attname,attstattarget from pg_catalog.pg_attribute where attrelid in ('t_eqjoinsel_mergejoinscansel_1'::regclass, 't_eqjoinsel_mergejoinscansel_2'::regclass) and attnum = 1;


INSERT INTO t_eqjoinsel_mergejoinscansel_1 SELECT repeat( 'PostgreSQL', 100) || to_char(101 - g, '099') FROM generate_series(1, 100) g;
INSERT INTO t_eqjoinsel_mergejoinscansel_1 SELECT repeat( 'PostgreSQL', 100) || to_char(101 - g, '099') FROM generate_series(1, 100) g;

insert into t_eqjoinsel_mergejoinscansel_2 select * from t_eqjoinsel_mergejoinscansel_1;

DO $$
BEGIN
    FOR i IN 1..100 LOOP
        INSERT INTO t_eqjoinsel_mergejoinscansel_2 SELECT repeat( 'PostgreSQL', 100) || to_char(g, '099') FROM generate_series(i, 100) g;
    END LOOP;
END $$;

with t1 as (select substring(name FOR 10) || '...' || substring(name FROM 1002 FOR 3) as name from t_eqjoinsel_mergejoinscansel_1)
select * from (select name ,count(*) as my_count from t1 group by name) order by 2,1 ;

with t1 as (select substring(name FOR 10) || '...' || substring(name FROM 1002 FOR 3) as name from t_eqjoinsel_mergejoinscansel_2)
select * from (select name ,count(*) as my_count from t1 group by name) order by 2,1 ;

----------------

analyze t_eqjoinsel_mergejoinscansel_1, t_eqjoinsel_mergejoinscansel_1;

----------------
WITH s AS (SELECT stakind1,stanumbers1, stavalues1::text AS values_text
 FROM pg_catalog.pg_statistic
 WHERE starelid = 't_eqjoinsel_mergejoinscansel_1'::regclass AND staattnum = 1
),
v AS ( SELECT ordinality AS n, value
 FROM s, LATERAL unnest( string_to_array(trim(both '{}' FROM values_text), ',' ) ) 
 WITH ORDINALITY AS u(value, ordinality)
),
f AS ( SELECT ordinality AS n, frequency
 FROM s, LATERAL unnest(stanumbers1) 
 WITH ORDINALITY AS u(frequency, ordinality)
)
,
s2 AS (SELECT stakind1,stanumbers1, stavalues1::text AS values_text
 FROM pg_catalog.pg_statistic
 WHERE starelid = 't_eqjoinsel_mergejoinscansel_2'::regclass AND staattnum = 1
),
v2 AS ( SELECT ordinality AS n, value
 FROM s2, LATERAL unnest( string_to_array(trim(both '{}' FROM values_text), ',' ) ) 
 WITH ORDINALITY AS u(value, ordinality)
),
f2 AS ( SELECT ordinality AS n, frequency
 FROM s2, LATERAL unnest(stanumbers1) 
 WITH ORDINALITY AS u(frequency, ordinality)
)
select * from (
SELECT 't_eqjoinsel_mergejoinscansel_1' as relname, CASE 
  when s.stakind1 = 1 then '1-STATISTIC_KIND_MCV' 
  when s.stakind1 = 8 then '8-STATISTIC_KIND_MCV_VALUE_SORTED' 
  else NULL END AS MCV_TYPE
  ,length(v.value) as length
	,v.n as no, substring(v.value FOR 10) || '...' || substring(v.value FROM 1003 FOR 3) value, f.frequency
 FROM v JOIN f USING(n) JOiN s ON 1=1
  and substring(v.value FROM 1003 FOR 3)
  in ('000', '001', 
      '010', '020', '030', '040', '050', '060', '070', '080', '090', '100')
 ORDER BY v.n
)
union all 
(
SELECT 't_eqjoinsel_mergejoinscansel_2' as relname, CASE 
  when s.stakind1 = 1 then '1-STATISTIC_KIND_MCV' 
  when s.stakind1 = 8 then '8-STATISTIC_KIND_MCV_VALUE_SORTED' 
  else NULL END AS MCV_TYPE
  ,length(v.value) as length
	,v.n as no, substring(v.value FOR 10) || '...' || substring(v.value FROM 1003 FOR 3) value, f.frequency
 FROM v2 as v JOIN f2  as f USING(n) JOiN s2 as s ON 1=1
  and substring(v.value FROM 1003 FOR 3)
  in ('000', '001', 
      '010', '020', '030', '040', '050', '060', '070', '080', '090', '100')
 ORDER BY v.n
);


--generate 07-eqjoinsel_mergejoinscansel.sql
>07-eqjoinsel_mergejoinscansel.sql
for cf in 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2; do	echo "explain (SUMMARY, COSTS off) select * from t_eqjoinsel_mergejoinscansel_1 where name in (select name from t_eqjoinsel_mergejoinscansel_2);">>07-eqjoinsel_mergejoinscansel.sql; done

08-test_eqjoinsel_mergejoinscansel.sh
cat 07-eqjoinsel_mergejoinscansel.sql|psql xman7|grep "Planning Time"

-- run 08-test_eqjoinsel_mergejoinscansel.sh

>07-eqjoinsel_mergejoinscansel.out
sh 08-test_eqjoinsel_mergejoinscansel.sh >07-eqjoinsel_mergejoinscansel.out 2>&1

--get test result data
--1st eqjoinsel
cat 07-eqjoinsel_mergejoinscansel.out|grep "eqjoinsel()"|grep -n "eqjoinsel()"|awk 'NR%2==1' | awk '{print $NF'}
--2st eqjoinsel
cat 07-eqjoinsel_mergejoinscansel.out|grep "eqjoinsel()"|grep -n "eqjoinsel()"|awk 'NR%2==0' | awk '{print $NF'}
cat 07-eqjoinsel_mergejoinscansel.out|grep "mergejoinscansel()"|awk '{print $NF}'
cat 07-eqjoinsel_mergejoinscansel.out|grep "e:"|awk -F 'e:' '{print $2}'|awk '{print $1}'|sed 's/NOTICE://g'


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com







Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Hi hackers,

While working on dump/restore and postgres_fdw support for this patch [1], I'd like to get some
feedback on how to expose the MCV representation through pg_stats and pg_stats_ext_exprs.

The patch introduces a new statistics kind (kind 8) for MCVs sorted by value, while retaining the
existing frequency-ordered representation (kind 1). During restore, we need to know which 
representation the exported arrays use. Restoring value-ordered arrays as kind 1 could cause 
subsequent consumers to misinterpret their ordering.

Initially, I avoided adding columns to these views to preserve their existing result shapes. Instead, 
my revised pg_dump and postgres_fdw queries join pg_stats to the underlying pg_statistic catalog 
to obtain the statistics kind.

However, testing exposed a permission regression. A non-superuser with SELECT privilege on a table 
can read its corresponding rows from pg_stats, but the additional reference to pg_statistic fails with:
ERROR: permission denied for table pg_statistic


For the same role and table, the baseline pg_dump --statistics-only succeeds, while the revised query fails. 
Statistics import through postgres_fdw also fails when using a non-superuser remote mapping, although 
querying the foreign table's data succeeds. Using a remote superuser allows the statistics import to succeed.

I found two relevant precedents for extending the statistics views:
- Commit [bc3c8db8ae2f](https://github.com/postgres/postgres/commit/bc3c8db8ae2f899cfd65edce99fe9cf65caf1ed7) 
added range_length_histogram, range_empty_frac, and range_bounds_histogram to the end of pg_stats in PostgreSQL 17, 
along with a catalog version bump and updates to the documentation and regression test output.

- Commit [307447e6dbc0](https://github.com/postgres/postgres/commit/307447e6dbc035c0e6e7a8ce9cee704a3b710ee9) 
added the same fields to pg_stats_ext_exprs in PostgreSQL 19, also with a catalog version bump.

Current pg_dump code handles the range-statistics fields by checking the source server version and selecting NULL 
placeholders for servers predating PostgreSQL 17. I think a similar version-compatibility approach could work for 
the new MCV metadata.

My current proposal is to:
- Append a smallint column named most_common_vals_kind to both views. It would return the representation kind (1 or 8) 
corresponding to the most_common_vals and most_common_freqs actually exposed, and NULL when no MCV slot is present.

- Preserve the existing privilege checks and row-security filtering of both views, and have pg_dump and postgres_fdw obtain 
the kind through the views rather than accessing pg_statistic directly.

- For source servers predating this addition, assume kind 1 for their existing single-variable MCV representation. 
For expression statistics, include the kind in each exported JSON object.

- Update the catalog version, documentation, and relevant regression tests.

Appending a column would preserve the positions of existing columns, although clients that assume a fixed number of 
columns from SELECT * could still require adjustments.

Also, exposing the representation kind would not by itself address tools that assume MCV arrays are always 
frequency-ordered. The range-statistics precedents support extending these views, but do not directly resolve the 
compatibility implications of changing the MCV ordering.

I'd appreciate feedback on two related but distinct questions:
1. Would adding most_common_vals_kind to both pg_stats and pg_stats_ext_exprs be an appropriate way to address 
the statistics-export permission issue?
2. Should the public statistics views continue to guarantee frequency-ordered MCVs, with value-ordered statistics 
exposed through a separate interface? Or would explicitly exposing the representation kind be sufficient to support the new ordering?

I'd welcome suggestions, particularly on system view design, backward compatibility, and the behavior of dump/restore and postgres_fdw.

Thanks!

[1] https://commitfest.postgresql.org/patch/7302/


Attached test SQL and results:
====================for super role, ok
SELECT current_user, rolsuper FROM pg_roles WHERE rolname = current_user;
 current_user | rolsuper 
--------------+----------
 xman         | t
(1 row)

xman7=# 

SELECT s.attname, sat.stakind1
FROM pg_catalog.pg_stats AS s
LEFT JOIN pg_catalog.pg_statistic AS sat
  ON sat.starelid = 't_sort_mcv_100'::regclass
 AND sat.staattnum = 1
 AND sat.stainherit = s.inherited
WHERE s.schemaname = 'public' AND s.tablename = 't_sort_mcv_100' and sat.stakind1 in (1, 8) limit 10;
 attname | stakind1 
---------+----------
 name    |        8
(1 row)

xman7=#

====================for non super role, error
CREATE ROLE mcv_reader_1 NOLOGIN;
SET ROLE mcv_reader_1;
SELECT current_user, rolsuper FROM pg_roles WHERE rolname = current_user;
SELECT s.attname, sat.stakind1
FROM pg_catalog.pg_stats AS s
LEFT JOIN pg_catalog.pg_statistic AS sat
  ON sat.starelid = 't_sort_mcv_100'::regclass
 AND sat.staattnum = 1
 AND sat.stainherit = s.inherited
WHERE s.schemaname = 'public' AND s.tablename = 't_sort_mcv_100' and sat.stakind1 in (1, 8) limit 10;


xman7=# CREATE ROLE mcv_reader_1 NOLOGIN;
CREATE ROLE
xman7=# SET ROLE mcv_reader_1;
SET
xman7=> SELECT current_user, rolsuper FROM pg_roles WHERE rolname = current_user;
 current_user | rolsuper 
--------------+----------
 mcv_reader_1 | f
(1 row)

xman7=> SELECT s.attname, sat.stakind1
FROM pg_catalog.pg_stats AS s
LEFT JOIN pg_catalog.pg_statistic AS sat
  ON sat.starelid = 't_sort_mcv_100'::regclass
 AND sat.staattnum = 1
 AND sat.stainherit = s.inherited
WHERE s.schemaname = 'public' AND s.tablename = 't_sort_mcv_100' and sat.stakind1 in (1, 8) limit 10;
ERROR:  permission denied for table pg_statistic
xman7=> 




regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com



Re: Optimize MCV stats for sortable types and utilize sorted-order properties

I write:
>Original
>From: ZizhuanLiu X-MAN <44973863@qq.com>
>Date: 2026-10-18 21:20
>To: pgsql-hackers 
>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>
>
>I write:
>>Original
>>From: ZizhuanLiu X-MAN <44973863@qq.com>
>>Date: 2026-10-17 20:06
>>To: pgsql-hackers 
>>Cc: Ilia Evdokimov , tgl , tomas , dean.a.rasheed , guofenglinux 
>>Subject: Re: Optimize MCV stats for sortable types and utilize sorted-order properties
>>......
>>The results are as follows:
>>  - var_eq_const():    The patch version is, on average, 43.88% faster than master.
>>  - mcv_selectivity(): The patch version is, on average, 39.02% faster than master.
>>......
>
>
>Hi,
>
>Using the same testing methodology, I also tested eqjoinsel(), mergejoinscansel(), and EXPLAIN planning time.
>
>The results are summarized below.
>- Execution plans: Master and the patch produce identical plans for the tested SQL cases.
>   See the 02-stats_data_explain sheet in the attached XLS file.
>- Performance: The patch shows substantial improvements in both eqjoinsel() and mergejoinscansel(),
>   as well as in planning time. See the 03-Raw_test_data_analyze and 03-test_data_analyze_2 sheets.
>
>Some measurements for master were anomalous. To make the comparison fairer, 03-test_data_analyze_2 excludes
>those anomalous master measurements and recalculates the results using the remaining measurements and the
>same methodology for both master and the patch. The results from both data sets are shown below.
>
>Metric                  03-Raw_test_data_analyze      03-test_data_analyze_2
>eqjoinsel()             96.46%                                      95.08%
>mergejoinscansel()      80.23%                                      74.17%
>EXPLAIN planning time   91.90%                                      89.05%

Additional Performance Test Results for Common Data Types

Hi hackers,

I've conducted additional performance tests to evaluate the impact of this patch on common data types and operations.

1. Test methodology
The previous tests primarily used long text strings (over 1,000 characters) with a case_insensitive collation, 
which is a relatively specialized scenario.

The new tests cover common data types, including int4 and text, and the following operations:
- VAR vs. CONST: =, <, <=, >, >=
- JOIN: scenarios involving eqjoinsel() and mergejoinscansel()

Each test was run 104 times. The first two runs were discarded as warm-up runs, and the arithmetic mean of the remaining 102 runs was used.
All execution times below are in milliseconds (ms). The time reduction percentage is calculated relative to master.

2. Test results
For the test cases listed below, master and the patch produce the same execution plan paths and estimated row counts.

2.1 var_eq_const()
Test SQL:
EXPLAIN (SUMMARY, COSTS OFF)  SELECT * FROM int4_n100_uniform WHERE id = 51;

                                  master (ms)   patch (ms)  Time reduction (%)
var_eq_const()              0.027            0.011           60.77%
Planning time               0.385            0.203           47.22%


2.2 mcv_selectivity()
Test SQL: 
EXPLAIN (SUMMARY, COSTS OFF) SELECT * FROM int4_n100_uniform WHERE id < 51;

                               master (ms)  patch (ms)  Time reduction (%)
mcv_selectivity()            0.024       0.010          59.01%
Planning time                0.368       0.171          53.51%

2.3 JOIN: int4
Test SQL:
EXPLAIN (SUMMARY, COSTS OFF) SELECT * FROM int4_n100_uniform WHERE id IN (SELECT id FROM int4_n100_uniform);

                                      master (ms)   patch (ms)  Time reduction (%)
eqjoinsel()                         0.2505         0.0399          84.07%
mergejoinscansel()           0.34941      0.20912         40.15%
Planning time                   1.61837      0.77411         52.17%
Combined share of the
two functions (%)             37.07%         32.17%             -


2.4 JOIN: text
Test SQL:
EXPLAIN (SUMMARY, COSTS OFF)SELECT * FROM text_n100_uniform
WHERE id IN (SELECT id FROM text_n100_uniform);

                                      master (ms)   patch (ms)  Time reduction (%)
eqjoinsel()                        0.38018       0.04035         89.39%
mergejoinscansel()          0.61253       0.18803         69.30%
Planning time                  2.04057       0.66537         67.39%
Combined share of the
two functions (%)           48.65%          34.32%             -


3. Initial observations
These results indicate that, in the common data types and query scenarios covered by these tests, 
the patch reduces not only the execution time of the relevant selectivity estimation functions, but 
also the overall planning time.

In the JOIN tests, both eqjoinsel() and mergejoinscansel() show lower execution times, accompanied
by substantial reductions in overall planning time.

In the earlier tests using long text strings with a case_insensitive collation, the combined share of eqjoinsel()
and mergejoinscansel() in the overall planning time decreased from 93.60% to 59.19%. This is currently the 
scenario with the largest observed reduction in overall planning time.

The additional tests suggest that the improvements are not limited to that specialized scenario. Reductions
in overall planning time were also observed with the common int4 and text test cases.

These are the current test results and preliminary observations. Feedback on the test methodology, interpretation 
of the results, and other scenarios worth testing would be welcome.


Thanks!

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Discussion: MCV statistics ordering and compatibility


Hi,

I'd like to share some thoughts on the current design and propose an alternative approach for discussion.

1. Current approach
The current approach is to modify compute_scalar_stats() so that:
- For non-sortable data types, we continue to generate kind 1 (STATISTIC_KIND_MCV), 
   with MCV entries sorted by frequency (numbers[]).
- For sortable data types, we generate only kind 8 (STATISTIC_KIND_MCV_VALUE_SORTED), 
   with MCV entries sorted by value (values[]).

2. Potential performance benefits
Several planner functions can benefit from having MCV entries sorted by value, including
var_eq_const(), var_eq_non_const(), mcv_selectivity(), ineq_histogram_selectivity(), booltestsel(),
eqjoinsel(), and get_variable_range().

These functions handle operations such as =, <, <=, >, >=, !=, equality joins, and retrieving the
minimum and maximum values from statistics.

When value-sorted MCV statistics are available, operations that need to compare MCV values
can take advantage of boundary checks or binary search. Depending on the specific operation,
this can reduce the number of comparisons from O(N) or O(N2) to O(1) or O(log N), respectively.
This substantially reduces the number of value comparisons and the associated cost of potentially
expensive comparison functions.

(I haven't yet evaluated the impact on networkjoinsel_inner() and networkjoinsel_semi().)

The function-level and EXPLAIN timing results are available in [4]. These measurements were taken
using a debug build; I'll provide additional results using a release build later.

3. Compatibility concerns with the current approach
Although we can adjust the relevant internal logic to accommodate the new statistics kind, changing
the existing MCV representation may break compatibility for consumers that obtain MCV statistics
through hooks or the pg_stats, pg_stats_ext, and pg_stats_ext_exprs views.

Maintaining compatibility in statistics import/export and pg_dump-related functionality also becomes
difficult, particularly when the statistics kind (1 or 8) needs to be preserved and propagated.

See [5] for more details.

4. An alternative approach: generate both kinds of MCV statistics
After studying the discussions in [1], [2], and [3], I've been considering another approach:

For sortable data types, generate both:
- Kind 1 (STATISTIC_KIND_MCV), with entries sorted by frequency.
- Kind 8 (STATISTIC_KIND_MCV_VALUE_SORTED), with entries sorted by value.

This could address the compatibility concerns described in point 3, while allowing the planner to use
whichever representation is more appropriate for a particular operation.

However, this approach introduces two concerns:

4.1. Additional statistics slot
It would exceed the current limit of five statistics slots (STATISTIC_NUM_SLOTS), potentially requiring
us to increase the limit to six, along with the corresponding catalog changes and related adjustments.

For example, I have observed the following slot usage for an array column with a low statistics target:
stakind1 = 8
stakind2 = 2
stakind3 = 3
stakind4 = 4
stakind5 = 5

This shows that all five slots can already be occupied in some cases. Therefore, simply adding kind 1
alongside kind 8 would require an additional slot in such cases.

The SQL used to reproduce this result is provided at the end.

4.2. Duplicate-looking statistics
For sortable data types, both kinds contain the same MCV values and frequencies, differing only in
their sort order. At first glance, storing both may seem redundant.

5. Why I think storing both may be worthwhile
I don't think these two representations are redundant in terms of their purpose.

A similar analogy would be indexes on (a ASC, b ASC) and (b ASC, a ASC): they contain the same
underlying table data, but their different ordering makes them useful for different access patterns.

In this case, storing both representations is a trade-off between additional storage and better access efficiency.
It could preserve the existing frequency-sorted representation for compatibility while also providing the
value-sorted representation for planner optimizations.

Given how many common planner operations could benefit from value-sorted MCV statistics, I think the potential
benefits may justify this trade-off.

I'd appreciate your thoughts on this alternative approach. In particular, do you think maintaining both representations,
even at the cost of an additional statistics slot, is a reasonable design?

Any comments or suggestions are welcome.


[1] https://www.postgresql.org/message-id/flat/AANLkTikiruxOYh6jE_ETK7u4sEW6VXXqFK3Xn0-zVxoe%40mail.gmail.com
[2] https://www.postgresql.org/message-id/flat/AANLkTin02SOXNzFxju74Hf-uqhAmymR0-hyAodi4G0Of%40mail.gmail.com
[3] https://www.postgresql.org/message-id/flat/20111229163500.GA647%40tornado.leadboat.com#23f5d75556258244556caeb32eb2daef
[4] https://www.postgresql.org/message-id/tencent_0AD51A01E1E1DBC468A12768BEDD2C53A809%40qq.com
[5] https://www.postgresql.org/message-id/tencent_0F362A5AB80984EF5B4B1CEAA7C61AF8C907%40qq.com



sql:
DROP TABLE IF EXISTS test_array_stats;

CREATE TABLE test_array_stats
(
    id  int,
    arr int[]
);
alter table test_array_stats alter column arr set statistics 2;

INSERT INTO test_array_stats
SELECT
    i,
    CASE
        WHEN i % 10 = 0 THEN ARRAY[1, 2, 3]
        WHEN i % 10 = 1 THEN ARRAY[1, 2, 4]
        WHEN i % 10 = 2 THEN ARRAY[1, 2, 5]
        WHEN i % 10 = 3 THEN ARRAY[1, 3, 4]
        WHEN i % 10 = 4 THEN ARRAY[2, 3, 5]
        WHEN i % 10 = 5 THEN ARRAY[3, 4, 5]
        WHEN i % 10 = 6 THEN ARRAY[1, 4, 5]
        WHEN i % 10 = 7 THEN ARRAY[2, 4, 5]
        WHEN i % 10 = 8 THEN ARRAY[1, 2, 3, 4]
        ELSE ARRAY[2, 3, 4, 5]
    END
FROM generate_series(1, 100000) AS i;

alter table test_array_stats alter column arr set statistics 2;
ANALYZE test_array_stats;

select * FROM pg_statistic where starelid = 'test_array_stats'::regclass and staattnum = 2 \gx
select * FROM pg_statistic where starelid = 'test_array_stats'::regclass and staattnum = 2 \gx
-[ RECORD 1 ]-------------------------------------------------------------------
starelid    | 24895
staattnum   | 2
stainherit  | f
stanullfrac | 0
stawidth    | 33
stadistinct | 8
stakind1    | 8
stakind2    | 2
stakind3    | 3
stakind4    | 4
stakind5    | 5
staop1      | 1070
staop2      | 1072
staop3      | 1072
staop4      | 96
staop5      | 96
stacoll1    | 0
stacoll2    | 0
stacoll3    | 0
stacoll4    | 0
stacoll5    | 0
stanumbers1 | {0.20133333,0.19743334}
stanumbers2 | 
stanumbers3 | {0.13585752}
stanumbers4 | {0.50303334,0.70283335,0.7971,0.5963333,0.5988333,0.0101,0.7971,0}
stanumbers5 | {3,4,3.1981332}
stavalues1  | {"{1,2,3}","{3,4,5}"}
stavalues2  | {"{1,2,3,4}","{1,3,4}","{2,4,5}"}
stavalues3  | 
stavalues4  | {1,2,3,4,5}
stavalues5  | 

xman7=# 


n_distinct             | 8
most_common_vals       | {"{1,2,3}","{3,4,5}"}                 ==============8
most_common_freqs      | {0.20133333,0.19743334}    ==============8
histogram_bounds       | {"{1,2,3,4}","{1,3,4}","{2,4,5}"}    ==============2
correlation            | 0.13585752    ==============3
most_common_elems      | {1,2,3,4,5}     ==============4
most_common_elem_freqs | {0.50303334,0.70283335,0.7971,0.5963333,0.5988333,0.0101,0.7971,0}   ==============4
elem_count_histogram   | {3,4,3.1981332}  ==============5
range_length_histogram |  ======6
range_empty_frac       | =======6
range_bounds_histogram | =======7

xman7=# 





regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Hi hackers,

I have revisited the four int4/text cases from my earlier performance
report [1], first retesting v15 and then comparing it with v16. The
earlier results were obtained with debug builds. In the current release
tests, I could not reproduce the magnitude of the speedups reported
there: joins still benefit under the tested conditions, but the two
scalar cases do not show an overall planning-time improvement.

I have also implemented the paired-MCV design proposed in [2]. Below
are the release results and the main implementation changes.

The comparison uses three versions based on master 8b529705d153:
master, master with the v15 changes from the earlier mail, and master
with the v16 changes. All were built with -O2, --disable-cassert, and
--disable-debug. Function timing code and its NOTICE output were removed
to measure overall EXPLAIN Planning Time without that instrumentation.

Each version used a fresh instance with the same test data: 20,000 rows,
100 distinct values, and 100 MCVs for each tested column. The text case
uses 12-character strings with the "C" collation. Tests ran serially,
with version order rotated across 20 rounds. Each case/round/version
used one connection and 104 EXPLAINs; the first two were discarded as
warm-up runs and the remaining 102 were averaged. Raw outputs were
retained. The int4 values are multiples of ten, so =51 is an interior
MCV miss and <51 has its boundary between MCV values.

The following are arithmetic means across all 20 rounds, without
removing outliers. Times are in milliseconds. Reduction is calculated
as (master - patch) / master, so a negative value means a regression.

Case        master       v15        v16      v15 reduction  v16 reduction
---------  ---------  ---------  ---------   -------------  -------------
int4 =51   0.041766   0.062891   0.043947       -50.58%         -5.22%
int4 <51   0.040116   0.045483   0.042681       -13.38%         -6.39%
int4 IN    0.132870   0.120811   0.113871        +9.08%        +14.30%
text IN    0.162116   0.140652   0.136496       +13.24%        +15.80%

The v15 int4 =51 mean is particularly affected by large timing spikes.
For context, pooled medians of all post-warm-up samples are:

Case        master       v15        v16
---------  ---------  ---------  ---------
int4 =51   0.039000   0.040000   0.040000
int4 <51   0.038000   0.040000   0.039000
int4 IN    0.124000   0.115000   0.113000
text IN    0.161000   0.130000   0.132000

Thus the large mean regression in the v15 equality case should not be
interpreted as its typical overhead. Both summaries still show no
scalar-query benefit and lower planning times for the two join cases.

In [1], the debug-build tests reported Planning Time reductions of
47.22%, 53.51%, 52.17%, and 67.39% for these four cases. The current
release measurements show much smaller join gains and do not support
carrying those earlier percentages over to release builds. This is not
a comparison with identical build settings, and the master baseline has
also changed; I have not established which factors explain the gap.

All three versions used an MCV hash threshold of 202. With 100 MCVs on
each input, this deliberately exercises non-hash matching. The default
release threshold is 200, so the join results characterize that non-hash
comparison and do not establish a benefit over master's default hash
path. A default-threshold comparison is also needed.

A separate diagnostic equality join also exposed a v15 estimation
difference: 3,960,000 rows versus 4,000,000 for master, v16, and the
actual result. The old v15 implementation was retained unchanged for
the historical comparison; these timing results should not be taken as
evidence that all versions produce identical estimates.

As for v16, the main changes from v15 are:

* Retain kind 1 in descending frequency order and add kind 8 in ascending
  value order, containing the same value-frequency pairs and collation.
  Kind 1 records the equality operator; kind 8 records the actual '<'
  ordering operator.

* Generate kind 8 after selecting the final kind-1 members. Sort their
  positions in the already sorted sample and reuse that order for
  histogram construction, avoiding another round of value comparisons.

* Use ordered MCVs for compatible endpoint/binary-search lookups in
  var_eq_const() and mcv_selectivity(), ordered non-hash matching in
  eqjoinsel(), and endpoint retrieval in get_variable_range() and
  get_stats_slot_range(). Check operator semantics, types, collation,
  and access to the actual comparator. Use kind 1 when frequency order
  is required. Network selectivity code continues to use kind 1.

* Increase STATISTIC_NUM_SLOTS from five to six, since array statistics
  can already occupy five slots. Keep the existing MCV view columns
  associated with kind 1, and append separate value-sorted columns to
  pg_stats and pg_stats_ext_exprs. Update statistics import, pg_dump,
  and postgres_fdw accordingly. Import accepts no MCVs, kind 1 alone,
  or a consistent pair of kinds 1 and 8, and rejects kind 8 alone.

The paired design preserves the meaning and ordering of the existing
MCV columns, but changes the catalog layout and view result shapes.
It also duplicates the MCV value/frequency payload and adds work during
ANALYZE and statistics access. The new tests do not yet establish that
the performance benefit generally justifies these costs.

These results reinforce Ilia's earlier concern [3] about cheap
comparisons on small MCV lists. Reducing comparison counts does not
necessarily reduce elapsed time once setup and statistics-access costs
are included. The next evaluation should distinguish regressions when
both versions use the existing path from gains when the patch uses an
ordered path, and examine list length, frequency skew, comparison cost,
and constant position.

My main concern is whether the measured gains justify the scope and
long-term maintenance cost. For sortable columns with MCVs, we would
store the same value-frequency pairs in two statistics slots instead
of one, and increase the catalog-wide slot limit from five to six.
The current patch already touches 27 files, with 3,445 insertions and
243 deletions, including comments, regression SQL, and expected output.

This is before any substantial optimization of network_selfuncs.c,
which currently has only changes to keep using kind 1 with the adjusted
interfaces. Further regression cases and validation are also still
needed, so the scope may grow further.

Given that scale, I am not yet convinced that the release-build gains
observed so far are compelling enough to justify the catalog changes,
additional storage, and implementation complexity. I would appreciate
feedback on whether there is a sufficiently strong case for pursuing
this design, or whether a narrower approach would be more worthwhile.

[1] https://www.postgresql.org/message-id/tencent_0AD51A01E1E1DBC468A12768BEDD2C53A809%40qq.com
[2] https://www.postgresql.org/message-id/tencent_70A009DE6F5DCB02EADB467EF8CA36345A07%40qq.com
[3] https://www.postgresql.org/message-id/87fde6ac-3647-4fce-be92-af27f6c132fa%40tantorlabs.com


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: Optimize MCV stats for sortable types and utilize sorted-order properties

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Subject: MCV optimization: design, evolution, trade-offs, and current results (v16)

Hi

This proposal reduces planner CPU work by storing MCV entries in value
order, so selectivity estimation can avoid repeated predicate calls. It
uses the existing per-column/per-expression MCV data. The current v16
design preserves frequency order as well; its storage and catalog costs
still need to be justified by performance evidence.

The design evolved as follows:

- Master:
  Representation: Kind 1, decreasing frequency order; five slots; Reason
  and trade-off: Supports frequency-based consumers; value lookups
  usually scan the list.
- Earlier patches, including v6–v15:
  Representation: Kind 8 replaces kind 1 for sortable types; five slots;
  Reason and trade-off: Adds value ordering without a second stored
  copy, but changes existing MCV consumers and view semantics.
- v16:
  Representation: Keep kind 1 and add kind 8; six slots; Reason and
  trade-off: Preserves the existing frequency-ordered representation, at
  the cost of duplicated MCV data and a catalog change.

The replacement design also required propagating the representation kind
through import/export interfaces. An attempt to retrieve it by joining
the public statistics views to pg_statistic caused permission failures.
Exposing the kind alone would still leave consumers that assume
frequency order incompatible. These issues motivated the paired design.

In v16, ANALYZE selects the ordinary kind-1 members first, then
generates kind 8 from exactly those value-frequency pairs. Sorting their
positions in the already sorted sample supplies value order and is
reused for histogram construction. Kind 1 records =, kind 8 records the
actual < ordering operator, and both record the same collation. This
avoids reconstructing the ordering from equality metadata.

Consumers use the two representations as follows:

- var_eq_const():
  Use of value order: Endpoint checks and binary search for compatible
  equality; frequency order remains available for first-match scans.
- mcv_selectivity():
  Use of value order: Find a qualifying prefix/suffix for <, <=, >, >=,
  instead of evaluating the predicate for every MCV.
- eqjoinsel() and matching helpers:
  Use of value order: Merge matching for two ordered lists, or binary-
  search probes with one ordered input, on eligible non-hash paths.
  Semi/anti-join top-k selection is by frequency, retaining value order
  afterward.
- mergejoinscansel():
  Use of value order: Estimate merge-join scan start/end fractions using
  input ranges and inequality selectivity. Benefits indirectly from
  ordered MCV endpoints through the range helpers, and eligible
  mcv_selectivity() fast paths via scalarineqsel().
- get_variable_range() / get_stats_slot_range():
  Use of value order: Use endpoints when the stored ordering and
  requested ordering/collation agree.

The histogram excludes MCVs, so histogram bounds alone cannot replace
these MCV operations. The complexity improvement concerns value
comparisons: frequency summation, array loading, and top-k preparation
can still require linear work or sorting.

Ordered comparisons require compatible operators, types, collation, and
permission to invoke the actual comparator. Other cases retain predicate
evaluation, using kind 1 where first-match frequency order matters.
get_attstatsslot_mcv() supports explicit representation selection and
metadata-only probes. Network selectivity code continues to use kind 1.

Existing MCV columns in pg_stats and pg_stats_ext_exprs continue to
expose kind 1; separate most_common_vals_value_sorted /
most_common_freqs_value_sorted columns expose kind 8. Import, pg_dump,
and postgres_fdw are updated. Ordinary-column and expression imports
share validation: allow neither kind, kind 1 alone, or a consistent
pair; reject kind 8 alone. Validate ordering, operators/collation, and
matching pairs, including partial updates.

The additional slot is needed because array statistics can already
occupy five slots. This changes catalog layout, increases fixed
metadata, and duplicates the logical MCV value/frequency payload where
kind 8 exists. It does not imply that the whole pg_statistic relation
doubles. The patch touches 27 files, with 3,445 insertions and 243
deletions, including comments, SQL, and expected output.

Earlier performance reports used debug builds. The release reruns did
not reproduce those speedup magnitudes. Overall Planning Time reductions
below use arithmetic means; pooled-median reductions appear in
parentheses. Positive means faster than master.

Case      v15 vs master      v16 vs master
--------  -----------------  -----------------
int4 =51  −50.58% (−2.56%)   −5.22% (−2.56%)
int4 <51  −13.38% (−5.26%)   −6.39% (−2.63%)
int4 IN   +9.08% (+7.26%)    +14.30% (+8.87%)
text IN   +13.24% (+19.25%)  +15.80% (+18.01%)

These runs used master 8b529705d153, -O2, assertions/debug disabled, and
timing/NOTICE code removed. Fresh instances had 20,000 rows and 100
MCVs; text used 12-character strings with C collation. Twenty serial
rounds rotated version order; each connection discarded two warmups and
measured 102 EXPLAINs. Outliers particularly affect v15's equality mean.
Build settings and baseline differ from the earlier report, so the cause
of the gap is unresolved.

All versions used hash threshold 202, keeping 100+100 MCVs on non-hash
paths. Default release uses 200; benefits over that default hash path
remain unproven. The scalar cases show no overall benefit, and v16 is
not uniformly better than v15 across summaries. The historical v15
snapshot also has a join-estimate defect: a diagnostic query gives 3.96M
rows instead of 4M; v16 agrees with master and the actual result.

For imported frequency ties, value-based top-k
tie-breaking can choose different members from a kind-1 prefix; this is
documented. Remaining review points include that policy, additional
coverage/test portability, default-hash and fallback-path costs, and
crossover thresholds. Network code has only adaptation changes. The
local snapshot also retains diagnostic timers and the 202 override,
which must be separated from a production patch.

Thread: https://www.postgresql.org/message-id/flat/tencent_0489DF3C961BD4D48D32F04F6D6EB4301308%40qq.com
Release results: https://www.postgresql.org/message-id/tencent_5E363FDABF09F7EF03CB7A6AEEC60D78A307%40qq.com
Earlier debug results: https://www.postgresql.org/message-id/tencent_0AD51A01E1E1DBC468A12768BEDD2C53A809%40qq.com

Regards,
ZizhuanLiu (X-MAN)



regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com
FAQ