Skip to content

Optimize min/max aggregates using column statistics - #105197

Closed
zoomxi wants to merge 26 commits into
ClickHouse:masterfrom
zoomxi:statistic-agg
Closed

zoomxi wants to merge 26 commits into
ClickHouse:masterfrom
zoomxi:statistic-agg

Conversation

@zoomxi

@zoomxi zoomxi commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds an optimization that answers filterless min() and max() aggregation queries from per-part column statistics without reading column data, avoiding full scans.

How it works

When a query like SELECT min(x), max(x) FROM t runs on a MergeTree table with column statistics configured (via auto_statistics_types = 'basic'), the optimizer checks whether the aggregate results can be obtained from the per-part StatisticsBasic metadata. If all conditions are met, the query plan replaces the ReadFromMergeTree step with a ReadFromPreparedSource that produces the answer directly from statistics without reading column data.

The optimization applies when:

  • All aggregates are min() or max()
  • The table has auto_statistics_types = 'basic' and statistics have been materialized for the relevant columns
  • The table has no active mutations, patch parts, or lightweight deletes that would make stored statistics stale
  • For GROUP BY queries, the GROUP BY keys must map to partition key columns
  • If a filter is present, it must be computable from partition-level expressions and virtual columns

If any check fails the query silently falls back to a normal ReadFromMergeTree read.

SQL Examples

-- Create a table with column statistics
CREATE TABLE t (
    key UInt64,
    value Int32
) ENGINE = MergeTree ORDER BY key
SETTINGS auto_statistics_types = 'basic';

-- Insert data (statistics are materialized on insert)
SET materialize_statistics_on_insert = 1;
INSERT INTO t SELECT number, toInt32(rand() % 1000) FROM numbers(10000000);

-- This query is answered from per-part statistics — no column data is read
SELECT min(value), max(value) FROM t;

-- GROUP BY partition key is also supported
CREATE TABLE t2 (
    p UInt8,
    v UInt32
) ENGINE = MergeTree PARTITION BY p ORDER BY tuple()
SETTINGS auto_statistics_types = 'basic';

INSERT INTO t2 SELECT number % 10, number FROM numbers(10000000);

SELECT p, min(v), max(v) FROM t2 GROUP BY p ORDER BY p;

The optimization can be disabled via SET use_statistics_for_min_max_aggregation = 0.

Related PRs

Related: #93037

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Optimize min() and max() aggregate functions by utilizing per-part column statistics (basic) metadata when available, avoiding full data scans for queries. Controlled by the new setting use_statistics_for_min_max_aggregation.


Workflow [PR]
Sync PR [sync-upstream/pr/105197]

@rschu1ze

rschu1ze commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

@zoomxi Please explain in the PR message what this optimization is doing (yes, I can and will read the code, but still). Please include a SQL example. Also, there should ideally be a xml performance test that demonstrates that performance improves.

@zoomxi

zoomxi commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Please explain in the PR message what this optimization is doing (yes, I can and will read the code, but still). Please include a SQL example. Also, there should ideally be a xml performance test that demonstrates that performance improves.

Sorry for the late reply, and thanks for the review! I'll make time to work on your suggestions soon.

@zoomxi
zoomxi force-pushed the statistic-agg branch 2 times, most recently from c4e9db4 to 2a72ec7 Compare July 23, 2026 10:09
@zoomxi

zoomxi commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Added performance test column_statistics_minmax_aggregation.

Query Scenario Optimization ON Optimization OFF Speedup
SELECT min(v), max(v) FROM t 10M rows, no partition 0.002s 0.011s 5.5x
SELECT p, min(v), max(v) FROM t GROUP BY p 10M rows, 20 partitions 0.003s 0.024s 8.0x

@rschu1ze

Copy link
Copy Markdown
Member

@zoomxi I'm looking at above measurements, the queries with the optimization turned off run so fast already that I think they are already answered from metadata. My theory is that such queries are already answered from the per-part minmax statistics (which are different than the min-max skip index and the basic statistics which also store min-max information). If that is true, then the PR would replace one metadata lookup by another metadata lookup.

@zoomxi

zoomxi commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor Author

If that is true, then the PR would replace one metadata lookup by another metadata lookup.

@rschu1ze I double-checked, and the baseline queries are not answered from metadata.

Query 1: SELECT min(value), max(value) FROM perf_stats_minmax_no_part

  Optimization OFF :
  └── ReadFromMergeTree (default.perf_stats_minmax_no_part)
        Read type: Default
        Parts: 9 | Granules: 1223
        Output: value

  Optimization ON:
  └── ReadFromPreparedSource (_column_statistics_aggregation)
  Query 2: SELECT p, min(v), max(v) FROM perf_stats_minmax_part GROUP BY p ORDER BY p

  Optimization OFF:
  └── ReadFromMergeTree (default.perf_stats_minmax_part)
        Read type: Default
        Parts: 80 | Granules: 1260
        Output: p, v

  Optimization ON:
  └── ReadFromPreparedSource (_column_statistics_aggregation)

@rschu1ze

Copy link
Copy Markdown
Member

Will check later, no time this week

@vdimir vdimir added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e67f61]

Summary: ✅


AI Review

Summary

This PR adds a ReadFromPreparedSource shortcut for eligible min/max queries that can be answered from per-part basic column statistics, plus focused regressions around filters, row policies, and parallel replicas. Most of the earlier correctness issues look addressed in the current HEAD, but one projection-setting regression remains: the new shortcut can preempt explicit aggregate projections entirely, so named/preferred projection selection is no longer preserved for these queries.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp:751] The new column-statistics candidate is built before explicit aggregate projections are analyzed, and once it succeeds the later projection-matching branch is skipped. That means a query on a table with both auto_statistics_types = 'basic' and a usable aggregate projection can no longer honor preferred_optimize_projection_name, and force_optimize_projection_name = 'p' now throws INCORRECT_DATA even though projection p matches. Decline the shortcut when a named/preferred projection is requested, or let explicit aggregate projections be analyzed first and take precedence.
Final Verdict

Changes required: preserve the existing named/preferred projection-selection contract when _column_statistics_aggregation is also applicable.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 364/407 (89.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 28, 2026
@zoomxi

zoomxi commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author
Clipboard_Screenshot_1785460222

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 338/379 (89.18%) · Uncovered code

Full report · Diff report

zoomxi added 4 commits August 20, 2026 22:23
Review feedback on ClickHouse#105197:

- `getColumnStatisticsAggregationBlock` now loads statistics for the
  aggregate argument columns only, via `loadStatistics(needed_columns)`,
  instead of materializing and caching the full per-part statistics map
  through `getEstimates` (which deserializes every column's statistics
  and pins them in the part arena).
- Explicitly require `StatisticsType::Basic` as the source of min/max
  bounds, since `minmax` statistics are deprecated and superseded by
  `basic` (ClickHouse#106048).
@rschu1ze

Copy link
Copy Markdown
Member

The per-part min-max statistics exist unconditionally for all parts. basic-type column statistics do exist for all parts as well, but only because setting auto_statistics_type forces them. I think it is more natural and correct to answer min/max aggregation functions from per-part min-max statistics.

zoomxi added 2 commits August 25, 2026 16:06
The shortcut fully replaces `ReadFromMergeTree` with `ReadFromPreparedSource`
and never runs `selectRangesToRead` / `AnalysisResult::checkLimits`, which
silently skipped the exceptions enforced there: `force_primary_key`,
`force_index_by_date`, `force_data_skipping_indices`, and
`max_partitions_to_read`. Decline the shortcut when any of these settings
apply (mirroring the guards of the text-index count shortcut), so the normal
read path keeps enforcing the same contract. `max_concurrent_queries` is
treated the same way since its `QueryIdHolder` cannot outlive the
optimization.

if (!candidates.minmax_projection)
/// Try to use column statistics for min/max aggregation.
if (!candidates.minmax_projection

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shortcut runs before explicit aggregate projections are analyzed, and once it fills column_statistics_projection the branch at if (!candidates.minmax_projection && !candidates.column_statistics_projection) is skipped entirely. That changes the projection-selection contract for min/max queries on tables that also have basic statistics: preferred_optimize_projection_name is ignored, and force_optimize_projection_name = 'p' now raises INCORRECT_DATA from optimizeTree.cpp:765-770 even when aggregate projection p is applicable.

Please either decline _column_statistics_aggregation when a named/preferred projection is requested, or analyze the real aggregate projections first and let them win when one matches.

@zoomxi

zoomxi commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

The per-part min-max statistics exist unconditionally for all parts. basic-type column statistics do exist for all parts as well, but only because setting auto_statistics_type forces them. I think it is more natural and correct to answer min/max aggregation functions from per-part min-max statistics.

@rschu1ze True that the per-part min-max metadata exists unconditionally — but it currently includes only partition key columns, so for min()/max() on non-key columns, basic statistics is the only part-level min/max metadata that can cover them.

Given that #115738 pursues the same goal with exactly this layering, I'm closing this PR in favor of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants