> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to enable column statistics for JOIN optimization when compatibility is set to an older version

> With a compatibility setting below 26.4 in the default profile, tables get no automatic column statistics after an upgrade. Enable them per table and backfill existing parts.

Since version 26.4, `MergeTree` tables collect column statistics automatically, and the query optimizer uses them to estimate filters and to choose the order of `JOIN`s. If the [`compatibility`](https://clickhouse.com/docs/reference/settings/session-settings/compatibility#compatibility) setting of the default profile is set to a version below 26.4, an upgraded server keeps the old default and creates no statistics. You can still enable them table by table: set `auto_statistics_types` on the table and materialize the statistics for existing parts. The optimizer uses statistics as soon as they exist.

In ClickHouse Cloud, the service-level `compatibility` value is fixed when the service is created and does not change on upgrades, see [Version compatibility](https://clickhouse.com/docs/products/cloud/features/admin-features/upgrades.md#version-compatibility).

## Why the tables have no statistics

`compatibility` reverts every default that changed after the given version. These are the relevant values in version 26.12:

| Setting | Default | `compatibility = '26.2'` | `compatibility = '25.11'` |
| - | - | - | - |
| `auto_statistics_types` (`MergeTree` setting) | `basic, uniq_v2` | empty | empty |
| `allow_statistics` | `1` | `0` | `0` |
| `use_statistics` | `1` | `1` | `1` |
| `materialize_statistics_on_insert_max_table_size` | `26843545600` | `0` | `0` |
| `use_statistics_for_part_pruning` | `1` | `0` | `0` |
| `enable_join_transitive_predicates` | `1` | `0` | `0` |
| `enable_join_runtime_filters` | `1` | `1` | `0` |
| `query_plan_optimize_join_order_limit` | `10` | `10` | `1` |

The default of `auto_statistics_types` became non-empty in 26.4, and `allow_statistics` was turned on in 26.3. `use_statistics` stays on with every value of `compatibility`, which is why statistics are used once they are there.

Server-wide defaults of `MergeTree` settings are derived once from the `compatibility` value of the default profile. Raising `compatibility` for a user, a session or a query does not change them, so `auto_statistics_types` has to be set on each table.

To see what your server uses:

```sql theme={null}
SELECT name, value
FROM system.merge_tree_settings
WHERE name = 'auto_statistics_types';

SELECT name, value
FROM system.settings
WHERE name IN ('compatibility', 'allow_statistics', 'use_statistics')
ORDER BY name;
```

```text theme={null}
   ┌─name──────────────────┬─value─┐
1. │ auto_statistics_types │       │
   └───────────────────────┴───────┘
   ┌─name─────────────┬─value─┐
1. │ allow_statistics │ 0     │
2. │ compatibility    │ 26.2  │
3. │ use_statistics   │ 1     │
   └──────────────────┴───────┘
```

## Enable statistics on a table

The example below was run on version 26.12 with `compatibility = '26.2'`. Two tables are joined, and the query names the small table first:

```sql theme={null}
CREATE TABLE customers
(
    customer_id UInt32,
    country LowCardinality(String)
)
ENGINE = MergeTree
ORDER BY customer_id;

CREATE TABLE orders
(
    order_id UInt64,
    customer_id UInt32,
    amount Decimal(18, 2)
)
ENGINE = MergeTree
ORDER BY order_id;

INSERT INTO customers SELECT number, ['DE', 'FR', 'NL', 'ES'][number % 4 + 1] FROM numbers(10000);
INSERT INTO orders SELECT number, number % 10000, number % 500 FROM numbers(1000000);

SELECT trimLeft(explain) AS plan
FROM
(
    EXPLAIN keep_logical_steps = 1, actions = 1
    SELECT count()
    FROM customers AS c
    INNER JOIN orders AS o ON o.customer_id = c.customer_id
    WHERE c.country = 'DE'
)
WHERE explain LIKE '%Join:%' OR explain LIKE '%ResultRows%';
```

```text theme={null}
   ┌─plan──────────────────────────────────────┐
1. │ Join: c[no_stats~?] ⋈ o[no_stats~1000000] │
2. │ ResultRows: unknown                       │
   └───────────────────────────────────────────┘
```

Without statistics the optimizer has no estimate for the filtered `customers` table and keeps the order of the query, so the hash table is built from the one million rows of `orders`.

First, declare the statistics. This changes only the table metadata and applies to all parts written from now on, by inserts and by merges:

```sql theme={null}
ALTER TABLE customers MODIFY SETTING auto_statistics_types = 'basic, uniq_v2';
ALTER TABLE orders MODIFY SETTING auto_statistics_types = 'basic, uniq_v2';
```

For a new table, add `SETTINGS auto_statistics_types = 'basic, uniq_v2'` to `CREATE TABLE`.

Then build statistics for the parts that already exist. This is a mutation that reads the columns of every part and writes their statistics. On a large table, start with the columns used in `JOIN` and `WHERE` conditions. A `compatibility` value below 26.3 sets `allow_statistics = 0`, so the statement needs `allow_statistics = 1`; without it, it fails with `Alter table with statistics is disabled. Turn on allow_statistics.`

```sql theme={null}
ALTER TABLE customers MATERIALIZE STATISTICS ALL SETTINGS allow_statistics = 1, mutations_sync = 1;
ALTER TABLE orders MATERIALIZE STATISTICS customer_id SETTINGS allow_statistics = 1, mutations_sync = 1;
```

`mutations_sync = 1` makes the statement wait for the mutation; leave it out on large tables and follow the progress in `system.mutations`. The `statistics` column of `system.parts_columns` shows what each part has:

```sql theme={null}
SELECT table, column, statistics, count() AS parts
FROM system.parts_columns
WHERE database = currentDatabase() AND table IN ('customers', 'orders') AND active
GROUP BY table, column, statistics
ORDER BY table, column;
```

```text theme={null}
   ┌─table─────┬─column──────┬─statistics─────────┬─parts─┐
1. │ customers │ country     │ ['Basic','UniqV2'] │     1 │
2. │ customers │ customer_id │ ['Basic','UniqV2'] │     1 │
3. │ orders    │ amount      │ []                 │     1 │
4. │ orders    │ customer_id │ ['Basic','UniqV2'] │     1 │
5. │ orders    │ order_id    │ []                 │     1 │
   └───────────┴─────────────┴────────────────────┴───────┘
```

The same `EXPLAIN` now shows estimates, and the smaller side is used to build the hash table:

```text theme={null}
   ┌─plan───────────────────────┐
1. │ Join: o[1000000] ⋈ c[2000] │
2. │ ResultRows: 201025         │
   └────────────────────────────┘
```

## Things to know

* **Use a release with the fix for stuck statistics mutations.** In earlier releases, `MATERIALIZE STATISTICS` and `DROP STATISTICS` started with `allow_statistics = 1` in the query failed forever when the server profile had `allow_statistics = 0`, and blocked all later mutations of the table. This is fixed in 26.10 and in the patch releases 26.7.31, 26.8.27 and 26.9.19.
* **Backfill the join keys.** If only some parts have statistics, estimates can be far off. In a test with statistics in one newly inserted part of 1,000 rows and none in the existing part of one million rows, the estimated join result was 1,001,000 rows; after the backfill of the join key it was 201,226.
* **You can backfill one partition at a time** with a column list: `ALTER TABLE orders MATERIALIZE STATISTICS customer_id IN PARTITION 202601`. `IN PARTITION` cannot be combined with `ALL`.
* **Inserts build statistics for tables of any size.** With `compatibility` below 26.4, `materialize_statistics_on_insert_max_table_size` is `0`, which removes the 25 GiB limit of newer versions. To get the limit back, set it for the users that insert: `ALTER USER etl_user MODIFY SETTING materialize_statistics_on_insert_max_table_size = 26843545600`.
* **Other optimizer defaults stay at the old values too**, for example `enable_join_transitive_predicates` and `use_statistics_for_part_pruning`. Enable the ones you want for a user with `ALTER USER ... MODIFY SETTING`; a setting that is set explicitly is not changed by `compatibility`. The alternative is a newer `compatibility` value for a user, a role or a session, as described on the [Version compatibility](https://clickhouse.com/docs/products/cloud/features/admin-features/upgrades.md#version-compatibility) page. That brings every other behavior change since the pinned version as well, so test your queries first.
* To check that a query used statistics, look at `ProfileEvents['LoadedStatistics']` in `system.query_log`. To compare plans, run the query with `SETTINGS use_statistics = 0`.

## Related pages

* [Column statistics](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/mergetree.md#column-statistics)
* [`ALTER TABLE ... STATISTICS`](https://clickhouse.com/docs/reference/statements/alter/statistics)
* [`compatibility` setting](https://clickhouse.com/docs/reference/settings/session-settings/compatibility#compatibility)
* [`auto_statistics_types`](https://clickhouse.com/docs/reference/settings/merge-tree-settings/other#auto_statistics_types)
