> ## 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 reduce memory usage of INSERT INTO ... SELECT (MEMORY_LIMIT_EXCEEDED)

> Why INSERT INTO ... SELECT can fail with MEMORY_LIMIT_EXCEEDED, and how max_insert_threads, max_threads and min_insert_block_size_rows trade memory for speed and number of parts.

An `INSERT INTO ... SELECT` keeps in memory the rows that are about to become new data parts: for every insert thread, a block of up to [`min_insert_block_size_rows`](https://clickhouse.com/docs/reference/settings/session-settings/min-insert#min_insert_block_size_rows) rows or [`min_insert_block_size_bytes`](https://clickhouse.com/docs/reference/settings/session-settings/min-insert#min_insert_block_size_bytes) bytes. If the query fails with `MEMORY_LIMIT_EXCEEDED` (code 241), reduce the number of insert threads first, and the size of the blocks second.

## The error

```text theme={null}
Code: 241. DB::Exception: Query memory limit exceeded: would use 497.40 MiB (attempt to allocate chunk of 92.08 MiB), maximum: 476.84 MiB. (MEMORY_LIMIT_EXCEEDED)
```

The first words name the limit that was reached: `Query` is [`max_memory_usage`](https://clickhouse.com/docs/reference/settings/session-settings/max-memory-usage#max_memory_usage), `User` is [`max_memory_usage_for_user`](https://clickhouse.com/docs/reference/settings/session-settings/max-memory-usage#max_memory_usage_for_user), and `(total)` is the memory limit of the server. When the message ends with `OvercommitTracker decision: Query was selected to stop by OvercommitTracker`, the limit of the user or of the server was reached and this query was chosen as the one to stop; see [Memory overcommit](https://clickhouse.com/docs/concepts/features/configuration/settings/memory-overcommit.md).

## Where the memory goes

1. The `SELECT` part reads the source with up to [`max_threads`](https://clickhouse.com/docs/reference/settings/session-settings/max-threads#max_threads) threads.
2. The rows flow into up to [`max_insert_threads`](https://clickhouse.com/docs/reference/settings/session-settings/max-insert#max_insert_threads) parallel insert streams, but not more than the number of streams that the `SELECT` produces.
3. Each insert stream collects rows until it has `min_insert_block_size_rows` rows (1048449 by default) or `min_insert_block_size_bytes` bytes (268402944 by default, about 256 MiB), whichever comes first. It then sorts the block and writes it as a new part, or as one part for each partition that the block touches.

A stream holds more than one such block at a time, because it collects the next block while the previous one is being written. The peak is therefore a few block sizes multiplied by the number of insert streams.

By default `max_insert_threads` is `0`, which means the number of CPU cores, so an `INSERT ... SELECT` writes in parallel. Before version 26.8 the default was `1`. The [settings reference](https://clickhouse.com/docs/reference/settings/session-settings/max-insert.md#max_insert_threads) lists the lower defaults that ClickHouse Cloud uses.

## Example

Create a source table with 6 million rows of about 120 bytes each, and an empty copy:

```sql theme={null}
CREATE TABLE events_src
(
    id UInt64,
    ts DateTime,
    user_id UInt32,
    message String
)
ENGINE = MergeTree
ORDER BY id;

INSERT INTO events_src
SELECT
    number AS id,
    toDateTime('2026-01-01 00:00:00') + intDiv(number, 100) AS ts,
    number % 10000 AS user_id,
    repeat(hex(cityHash64(number)), 6) AS message
FROM numbers(6000000);

CREATE TABLE events_dst AS events_src;
```

With four threads and a memory limit of 500 MB, copying the table fails with the error shown above:

```sql theme={null}
INSERT INTO events_dst
SELECT *
FROM events_src
SETTINGS max_memory_usage = 500000000, max_threads = 4, max_insert_threads = 4;
```

With one insert thread it succeeds, and so does a parallel insert with smaller blocks:

```sql theme={null}
TRUNCATE TABLE events_dst;

INSERT INTO events_dst
SELECT *
FROM events_src
SETTINGS max_memory_usage = 500000000, max_threads = 4, max_insert_threads = 1;

TRUNCATE TABLE events_dst;

INSERT INTO events_dst
SELECT *
FROM events_src
SETTINGS max_memory_usage = 500000000, max_threads = 4, max_insert_threads = 4, min_insert_block_size_rows = 100000;
```

The `SETTINGS` clause at the end of the query applies to both the `SELECT` and the `INSERT` part.

## What each setting costs

The following table shows the peak memory (`memory_usage` in [`system.query_log`](https://clickhouse.com/docs/reference/system-tables/query_log)) and the number of new parts for the same copy without a memory limit. The numbers are from one test machine and differ on yours, but the direction of each change is the same.

| `max_threads` | `max_insert_threads` | `min_insert_block_size_rows` | Peak memory | New parts |
| - | - | - | - | - |
| 4 | 4 | default | 989 MiB | 6 |
| 4 | 1 | default | 390 MiB | 6 |
| 1 | 1 | default | 359 MiB | 6 |
| 4 | 4 | 100000 | 243 MiB | 57 |
| 1 | 1 | 100000 | 52 MiB | 57 |
| 1 | 1 | 1000 | 12 MiB | 733 |

* **Fewer insert threads** lower the memory without changing the number of parts; the insert takes longer. Setting `max_threads = 1` has the same effect, because the insert cannot have more streams than the `SELECT`, but it also makes the reading single-threaded.
* **Smaller blocks** lower the memory further, but every block becomes a part: ten times smaller blocks mean ten times more parts for the background merges to process. For wide rows, lower `min_insert_block_size_bytes` instead of the number of rows.
* **Do not go too low.** Blocks are not split, only combined, so a value like `min_insert_block_size_rows = 1000` turns every block that the `SELECT` produces into a part of its own: 733 parts instead of 6 in this test. On a large table this can end with delayed inserts and the [`TOO_MANY_PARTS`](https://clickhouse.com/docs/resources/support-center/knowledge-base/troubleshooting/exception-too-many-parts) error.

You can measure your own query the same way:

```sql theme={null}
SYSTEM FLUSH LOGS;

SELECT
    type,
    formatReadableSize(memory_usage) AS memory,
    written_rows,
    ProfileEvents['InsertedWideParts'] + ProfileEvents['InsertedCompactParts'] AS new_parts,
    Settings['max_insert_threads'] AS max_insert_threads,
    Settings['min_insert_block_size_rows'] AS min_insert_block_size_rows
FROM system.query_log
WHERE event_date >= today() - 1
    AND type IN ('QueryFinish', 'ExceptionWhileProcessing')
    AND query_kind = 'Insert'
    AND query LIKE 'INSERT INTO events_dst%'
ORDER BY event_time_microseconds;
```

For the three inserts of the example it returns the following (the memory figures vary by some tens of megabytes between runs):

```text theme={null}
   ┌─type─────────────────────┬─memory─────┬─written_rows─┬─new_parts─┬─max_insert_threads─┬─min_insert_block_size_rows─┐
1. │ ExceptionWhileProcessing │ 407.37 MiB │      3069867 │         0 │ 4                  │                            │
2. │ QueryFinish              │ 391.06 MiB │      6000000 │         6 │ 1                  │                            │
3. │ QueryFinish              │ 228.04 MiB │      6000000 │        57 │ 4                  │ 100000                     │
   └──────────────────────────┴────────────┴──────────────┴───────────┴────────────────────┴────────────────────────────┘
```

## Other things to check

* **A failed `INSERT ... SELECT` is not rolled back.** The blocks that were written before the error stay in the target table. Remove them before you retry, for example with `TRUNCATE TABLE` if the table was empty before.
* **The `SELECT` itself can be the consumer.** If it has a `GROUP BY`, an `ORDER BY` or a `JOIN`, see [Memory limit exceeded for query](https://clickhouse.com/docs/resources/support-center/knowledge-base/performance-optimization/memory-limit-exceeded-for-query.md).
* **Wide target tables and many partitions.** Every block is split by the partition key of the target table, and every open part reserves write buffers for each column. See [Why does a small `INSERT` into a table with many columns use so much memory?](https://clickhouse.com/docs/resources/support-center/knowledge-base/troubleshooting/insert-high-memory-many-partitions-wide-table)
* The settings that make inserts larger and faster instead are described in [How do I solve the `TOO_MANY_PARTS` error during an `INSERT ... SELECT`?](https://clickhouse.com/docs/resources/support-center/knowledge-base/performance-optimization/insert-select-settings-tuning)
