Bookmarks
ReferenceData & AIVerified

ClickHouse

ClickHouse is a column-oriented database for big data analytics. In this reference: MergeTree, sorting keys, inserts, materialized views, replication.

checked 7 Nov · next check 14 Nov · 70 min read

Sections
14
Reading
70 min
Current version
26.10.3.7-stable
Written from
clickhouse.com/docs

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What ClickHouse is and how it works

ClickHouse is a column-oriented database for analytical queries (OLAP) over large volumes of data: events, logs, metrics and reports spanning billions of rows. A query reads only the columns it needs and runs in parallel across all cores, so aggregations take fractions of a second.

ClickHouse suits data that is mostly appended and then counted: inserts arrive as a stream, while queries aggregate and group. It does not suit transactional (OLTP) workloads with frequent point changes: UPDATE and DELETE are rare and expensive, performed as background operations.

The secret of the speed is columnar storage: the values of each column lie on disk separately, row by row. A query that averages one column needs none of the others, so the system reads only that column from disk. Values of the same kind in neighbouring rows compress well, which further cuts I/O.

A whole row on the left, one file per column on the right; the query reads only what it needs.

An insert is written to an immutable part of the data, and a background process continuously merges small parts into larger ones; rows inside a part are sorted by the primary key, and a sparse index points to granules — groups of 8,192 rows. A query finds granules by binary search and does not scan the rest. For details, see the sections “Table engines” and “Primary key, indexes and projections”.

Query execution is vectorised: operators process blocks of values rather than one row at a time, and a single query engages every CPU core. Values travel through the pipeline in groups, which lowers overhead and makes it possible to use SIMD processor instructions.

sqlAverage duration per hour: two of the three columns are read
CREATE TABLE events (    ts DateTime,    user_id UInt64,    duration_ms UInt32)ENGINE = MergeTreeORDER BY (ts, user_id); SELECT    toStartOfHour(ts) AS hour,    avg(duration_ms) AS avg_msFROM eventsWHERE ts >= now() - INTERVAL 7 DAYGROUP BY hourORDER BY hour;

How ClickHouse differs from PostgreSQL

PostgreSQL is a classic database for transactional (OLTP) workloads: each operation is carried out in full or rolled back, and its changes stay invisible to other transactions until commit. ClickHouse, by contrast, is built for analytics: data is mostly appended rather than modified, but aggregates over billions of rows are computed in real time.

FeatureClickHousePostgreSQL
Storageby columns, one file per columnby rows, whole rows
Transactionsreplaced by inserts, merges and mutationsACID transactions are the foundation
UPDATE and DELETErare mutations, performed in the backgroundordinary operations
Typical queryaggregation over billions of rowspoint reads and writes
Insertsin batches of 1,000 or more rowsa few rows per query

Choose ClickHouse when data arrives as a stream and needs to be counted: events, logs, metrics, dashboards, reports. Leave PostgreSQL to bookkeeping systems: an application needs frequent point changes and transactions. The two are often combined: transactions live in PostgreSQL, and its changes are replicated to ClickHouse for analytics.

What you need to know in advance

  • SQL: SELECT, WHERE, GROUP BY — covered in the SQL reference; only the ClickHouse dialect specifics are covered here.
  • Events and their dimensions: an event is a row, dimensions are columns; data types in ClickHouse are covered in the section “Data types and table schema”.
  • The table engine determines how data is stored and merged; the examples throughout this reference all use MergeTree — see the section “Table engines”.

Section sources

the section is written from these pages

Cheat sheet

Everyday ClickHouse commands: connecting with clickhouse-client, inspecting tables, inserting data, query plans, system tables and dangerous commands. Each command is covered in detail in its own section; substitute your own names in the examples (events in the analytics database).

clickhouse-client

The client connects to the server at localhost:9000 as the default user. In interactive mode the query is sent on Enter, and by default the result is rendered in the PrettyCompact format.

TaskCommand
Start the interactive clientclickhouse-client
Specify the server and userclickhouse-client --host example.com --user alice
Open your database straight awayclickhouse-client -d analytics
Run one query and exitclickhouse-client --query "SELECT 1"
Several queries in a rowclickhouse-client --query "SELECT 1; SELECT 2;"
Output in another formatclickhouse-client --query "SELECT 1" --format CSV
Wide rows verticallyclickhouse-client --query "SELECT 1" --vertical
Multi-line queries in the REPLclickhouse-client -m
Queries from a script fileclickhouse-client --queries-file job.sql
List databases and tables without leaving the client\l, then \d

Tables

TaskQuery
Tables in a databaseSHOW TABLES FROM analytics
Tables matching a patternSHOW TABLES FROM analytics LIKE 'ev%'
Columns of a tableDESCRIBE TABLE analytics.events
How the table is actually createdSHOW CREATE TABLE analytics.events

SHOW CREATE TABLE returns a ready CREATE TABLE statement with the table engine, sorting key and settings — handy for copying a schema between databases. Secrets in it are masked: displaying them requires the display_secrets_in_show_and_select and format_display_secrets_in_show_and_select settings as well as the displaySecretsInShowAndSelect privilege.

Inserting data

sqldata after FORMAT
INSERT INTO analytics.eventsFORMAT JSONEachRow{"user_id": 42, "event": "login", "ts": "2026-11-06 09:00:00"}
TaskQuery
Rows straight in the queryINSERT INTO t FORMAT JSONEachRow …
Load a file from the clientINSERT INTO t FROM INFILE 'data.csv' FORMAT CSV
Read a file as a tableINSERT INTO t SELECT * FROM file('data.csv', CSV)
Load an object from S3INSERT INTO t SELECT * FROM s3('https://…', 'CSV')

The format is declared explicitly: everything after FORMAT is treated as data, not as the query. FROM INFILE reads the file on the client side and detects compression from the file name extension, while file() and s3() stream the data on the server side.

Queries and plans

sqlwhich indexes were used
EXPLAIN indexes = 1SELECT count()FROM analytics.eventsWHERE ts >= '2026-11-01'SETTINGS use_query_condition_cache = 0,         use_skip_indexes_on_data_read = 0

In the output look at the Indexes key: PrimaryKey shows how many parts and granules the primary key eliminated, Skip — the data skipping indexes. A ratio such as Granules: 6/10 reads as “6 out of 10 read”. The trailing settings are required from version 25.9: without them the output is incomplete. This is how you check that a query does not read the whole table.

System tables

What to look atQuery
Table parts and their sizeSELECT name, rows, bytes_on_disk FROM system.parts WHERE database = 'analytics' AND table = 'events' AND active
What the queries did: time, rows, errorsSELECT query, query_duration_ms, read_rows FROM system.query_log WHERE type = 'QueryFinish' ORDER BY event_time DESC
Merges of parts in progressSELECT table, num_parts, progress FROM system.merges
Mutations and their progressSELECT table, command, is_done FROM system.mutations WHERE is_done = 0

system.query_log does not flush its records straight away — by default every 7.5 seconds, so to get the freshest records run SYSTEM FLUSH LOGS. A successful query produces two rows — QueryStart and QueryFinish; on an error the second row is replaced by one with the exception.

Dangerous commands

What it doesCommand
Delete a tableDROP TABLE analytics.events
Delete rows with a mutationALTER TABLE analytics.events DELETE WHERE user_id = 42
Delete a partition outrightALTER TABLE analytics.events DROP PARTITION '202611'
Force-merge everything into one partOPTIMIZE TABLE analytics.events FINAL

ALTER TABLE … DELETE is a heavy mutation: it rewrites every part that contains matching rows and writes a lot of data to disk. For one-off deletions in MergeTree the lightweight DELETE FROM … WHERE is usually faster: it hides the rows behind a mask and removes them during merges. OPTIMIZE TABLE … FINAL forces a merge of everything even when there is only one part; for deduplication add the DEDUPLICATE modifier to it. The documentation advises keeping OPTIMIZE for administration rather than for everyday work.

Section sources

the section is written from these pages

Installation and first run

The official way to install ClickHouse on Ubuntu and Debian is the APT repository packages.clickhouse.com with the clickhouse-server and clickhouse-client packages. Verify the installation with clickhouse-client --query "SELECT version()".

Linux: the APT repository

The packages are signed with the ClickHouse key. You connect the repository once and it then delivers updates. The repository line specifies the stable channel; change it to lts to receive only LTS releases.

bashon the host
sudo apt-get install -y apt-transport-https \  ca-certificates curl gnupg# the key the repository is signed withcurl -fsSL 'https://packages.clickhouse.com/rpm/lts/repodata/repomd.xml.key' \  | sudo gpg --dearmor -o /usr/share/keyrings/clickhouse-keyring.gpg# the repository; use lts instead of stableecho "deb [signed-by=/usr/share/keyrings/clickhouse-keyring.gpg \arch=$(dpkg --print-architecture)] https://packages.clickhouse.com/deb \stable main" | sudo tee /etc/apt/sources.list.d/clickhouse.listsudo apt-get update# the server and the clientsudo apt-get install -y clickhouse-server clickhouse-client

If you set a password for the default user during installation, the client needs the --password flag; without a password, plain clickhouse-client is enough.

bashon the host
sudo service clickhouse-server start# if a password was set during installationclickhouse-client --password

Docker

The official image clickhouse/clickhouse-server is built from the same deb packages. By default, the server in the container is reachable only from the Docker network, and the default user has no network access until a password is set — in the example the CLICKHOUSE_PASSWORD variable sets it. Publish ports 9000 (the native protocol) and 8123 (HTTP) on 127.0.0.1; what can be exposed to the outside is covered in the section “Security”.

bashon the host
docker run -d --name ch-server \  -p 127.0.0.1:8123:8123 -p 127.0.0.1:9000:9000 \  -e CLICKHOUSE_PASSWORD=change-me \  -v "$PWD/ch_data:/var/lib/clickhouse/" \  -v "$PWD/ch_logs:/var/log/clickhouse-server/" \  --ulimit nofile=262144:262144 \  clickhouse/clickhouse-server

The data lives in /var/lib/clickhouse/, the logs in /var/log/clickhouse-server/: without mounted directories the tables disappear along with the container. Connect to the running server:

bashon the host
docker exec -it ch-server clickhouse-client --password

Quick start

bashon the host
# downloads a binary for your OScurl https://clickhouse.com/ | sh# the server keeps data in the current directory./clickhouse server# in another terminal./clickhouse client

Run without a subcommand, ./clickhouse starts clickhouse-local: it processes local and remote files with no configuration, but keeps tables in a temporary directory, and they disappear after a restart. The ./clickhouse server variant keeps the data in the current directory and survives a restart.

On Linux and macOS (x86_64 and ARM64) the script also installs clickhousectl — a new official CLI for local installations and ClickHouse Cloud, with the alias chctl; the examples in this reference use clickhouse-client.

macOS and Windows

On macOS, ClickHouse runs natively: the quick install script supports macOS on x86_64 and ARM64, and the GitHub releases include official builds for macOS. On Windows, the Linux steps are performed inside Windows Subsystem for Linux (WSL).

Configuration

The server reads the main file /etc/clickhouse-server/config.xml; the settings for users, profiles and quotas live in users.xml by default, and the users_config element sets the path to it. Do not edit the main files: additional fragments go into the config.d/ and users.d/ directories, and the server merges them with the main files in lexicographic order of file names.

Check

bashon the host
clickhouse-client --query "SELECT version()"
textexample output
26.10.2.103

The reply is the server version; the number will be different on your machine: the client connected to localhost:9000 as the default user. If the connection fails, check whether the clickhouse-server service is running. Next come tables and data: the sections “Data types and table schema” and “Inserts and data modification”.

Section sources

the section is written from these pages

Data types and the table schema

The table schema in ClickHouse specifies a type for every column, and the choice of type affects both disk usage and query speed. There is one rule: take the smallest type that fits the data — UInt8 instead of Int64, Date instead of DateTime64, LowCardinality(String) instead of String for repeating values.

Numbers: the smallest sufficient type

Integers come signed (Int8, Int16, Int32, Int64, Int128, Int256) and unsigned (UInt8–UInt256): at the same bit width, an unsigned type doubles the range. Counters, quantities and ages are always non-negative — an unsigned type suits them. Choose the type by the actual range of values: UInt8 for flags and counters up to 255, UInt16 for values up to 65,535, UInt32 for identifiers up to 4.3 billion. The documentation recommends preferring UInt16 over Int32 when there are no negative values and the range fits.

Fractional numbers are Float32 and Float64: approximate types whose values may differ slightly from what was written. For money and exact totals this will not do: use Decimal(P, S). Here P is the total number of digits (from 1 to 76) and S is the number of digits after the decimal point. Decimal(12, 4) holds up to 8 digits before the decimal point and 4 after. Depending on P, the type is stored as Decimal32(S), Decimal64(S), Decimal128(S) or Decimal256(S).

Strings and repeating values

String is a string of arbitrary length: VARCHAR(255) and TEXT in a table definition are aliases of String, and ClickHouse ignores the length limit. FixedString(N) is exactly N bytes: it suits values of strictly fixed length such as country and currency codes. For strings with few distinct values — statuses, countries, licences — use LowCardinality(String): dictionary encoding compresses the column considerably. The benefit holds up to roughly 10,000 distinct values, and beyond 100,000 the column may end up worse than plain String.

For a finite set of values there are Enum8 and Enum16: up to 256 and up to 65,536 values. Numbers are stored in the database, but the insert validates the value: anything outside the declared list is rejected. LowCardinality(String) is often more convenient than Enum — more flexible and no less efficient, so the documentation recommends it for strings.

Date and time

Date is a date without a time of day, 2 bytes, spanning 1970 to 2149; Date32 is 4 bytes and spans 0000-01-01 to 9999-12-31. DateTime gives seconds, and DateTime64(P) adds P digits after the decimal point: 3 for milliseconds, 6 for microseconds, 9 for nanoseconds. The rule from the documentation: take the coarsest sufficient type — Date for dates without a time, DateTime instead of DateTime64 when milliseconds are not needed.

The time zone is set in the type declaration: DateTime('Asia/Tashkent'). The zone is not stored in the rows — only in the column metadata. Under the hood there is Unix time since the epoch, and the zone affects how strings are parsed on insert and how values are displayed.

sql
CREATE TABLE web_events(    event_time DateTime('Asia/Tashkent'),    user_id UInt64,    country_code FixedString(2),    status Enum8('new' = 1, 'paid' = 2, 'refund' = 3),    amount Decimal(12, 4),    tags Array(String),    attrs Map(String, String))ENGINE = MergeTreeORDER BY (event_time, user_id); SELECT country_code, count()FROM web_eventsWHERE event_time >= now() - INTERVAL 7 DAYGROUP BY country_code;

Here UInt64 for user_id leaves room for growth, FixedString(2) is the country code, Enum8 the three statuses and Decimal(12, 4) the amount. Array holds a list of tags in a single column, Map(String, String) — key–value pairs.

Nullable: the cost and the alternative

The Nullable(T) modifier allows a column to store NULL alongside ordinary values. The price is a separate file with a NULL-value mask: the column takes more space, and the documentation warns that Nullable almost always reduces performance. If you only need to show “there is no value”, a default value is simpler: 0 for numbers, an empty string, 1970-01-01 for dates. Use Nullable when an empty state has to be distinguished from zero or from an empty string.

Other types

For addresses there is IPv4 (4 bytes, like UInt32) and IPv6 (16 bytes): more compact than strings and with format checking. UUID is a 16-byte identifier; generateUUIDv4() produces a new one. Composite types: Array(T) is a list of values, Tuple is a tuple of values of different types, Map(K, V) is key–value pairs.

For semi-structured data there is the JSON type: the document is split into subcolumns, and a query reads only the paths it needs — for example attrs.user.agent. Path types can be set with hints when creating the table, and unneeded paths excluded with SKIP. Inserts are slower than into String, and so is reading the whole document — if the fields are not queried individually, store the document as String.

Denormalisation instead of joins

The analytical schema in ClickHouse is usually denormalised: reference fields are written straight into the fact table. Rarely changing reference data is attached with dictionaries — key-based access is faster than a JOIN with a reference table. How tables for such a schema are built is covered in the “Table engines” section.

Which type to choose: summary table

The type is chosen from the data: first rule out what does not apply — sign, precision, time zone, nullability — then take the smallest of what remains. Typical cases are summarised in the table below.

DataTypeWhy
Flag, counter up to 255UInt81 byte, values are non-negative
User identifierUInt32up to 4.3 billion values; beyond that — UInt64
Money, exact totalsDecimal(12, 4)exact arithmetic, no rounding error
A metric with a fractional partFloat64an approximate value is enough
Order statusEnum8values are validated on insert
Country codeFixedString(2)strictly 2 bytes
Country, status, licenceLowCardinality(String)dictionary encoding compresses the column
Arbitrary textStringlength is not limited
Date without a time of dayDate2 bytes instead of 4 in Date32
A moment with secondsDateTime('Asia/Tashkent')the time zone is pinned to the column
MillisecondsDateTime64(3)three digits after the decimal point
Client addressIPv44 bytes instead of a string of up to 15 characters
List of tagsArray(String)a list in a single column
Loose structureJSONpaths are read as subcolumns

Section sources

the section is written from these pages

Table engines: MergeTree and its family

The table engine determines how ClickHouse stores data and what it does with it during background merges. In practice the choice is almost always MergeTree or one of the engines of its family; the remaining engines are for special cases.

MergeTree stores a table as a set of parts sorted by the sorting key. The key is set by ORDER BY, the engine’s only required parameter: a table cannot be created without it, and if PRIMARY KEY is not given separately, the sorting key becomes the primary key. The primary key here is not about row uniqueness: it is a sparse index pointing to blocks of 8,192 rows — granules; for details, see the section “Primary key, indexes and projections”.

sql
CREATE TABLE events(    event_date Date,    event_time DateTime,    user_id UInt64,    url String)ENGINE = MergeTreePARTITION BY toYYYYMM(event_date)ORDER BY (user_id, event_time)TTL event_date + INTERVAL 6 MONTH DELETE;

PARTITION BY splits parts into partitions — usually by month via toYYYYMM(). This is a data management technique, not a tool for speeding up queries: partition pruning does help, but for speed the sorting key is tuned first. Parts in different partitions do not merge, so partitions that are too small — by day or by client — leave many small parts and get in the way of merges.

TTL sets the lifetime of rows: expired rows are deleted (the DELETE rule, the default) or moved to another disk or volume (TO DISK, TO VOLUME). There can be several rules, but no more than one DELETE.

Parts and merges

Each insert creates a separate part — the write merely puts sorted columns with an index on disk, which makes inserts cheap. Background merges continuously combine small parts into larger ones until they reach about 150 GB compressed; merged parts are marked inactive and are deleted a few minutes later. Hence the name: MergeTree — a “merge tree”.

The part name encodes the range of merged parts and the merge level.

Active parts are listed by the _part column, and all parts of the table by system.parts. Many small active parts are a sign of inserts that are too frequent; the remedy is inserting in large batches or asynchronous inserts (see the section “Inserting and changing data”).

The MergeTree family

The engines of the family repeat the design of MergeTree but change the behaviour during a merge: parts are not just put together but transformed. A merge is a background process that runs at an indefinite moment, so the transformation is not instant: fresh inserts stay unprocessed for a while.

EngineWhat it does during a mergeWhen to choose it
MergeTreenothing: combines parts into onethe universal default
ReplacingMergeTreekeeps one row per sorting key: the last one inserted, or the row with the highest version from the ver parameterdeduplication: repeated events, state with updates
SummingMergeTreereplaces rows with the same key with a single row, summing the numeric columnspre-aggregation of counters
AggregatingMergeTreereplaces rows with the same key with a single row holding partial states of aggregate functionsincremental aggregation, materialized views
CollapsingMergeTreedeletes pairs of rows with opposite values of the Sign column: 1 and -1frequent “updates” of an object by inserting the state and the cancellation
sql
CREATE TABLE users_state(    user_id UInt64,    name String,    updated_at DateTime)ENGINE = ReplacingMergeTree(updated_at)ORDER BY user_id;

The other engines

Special engines are rarely needed. Memory keeps data in RAM without compression and loses it when the server restarts; the Log family is a set of minimal engines for small tables of up to roughly a million rows; Null discards data — useful when the source data is needed only by a materialized view; Buffer accumulates inserts in memory and flushes them into another table — the documentation recommends asynchronous inserts instead.

Integration engines (Kafka, S3, PostgreSQL, MySQL and others) read and write the data of external systems, and Distributed distributes queries across the shards of the cluster — for details, see the section “Replication, shards and Keeper”.

Section sources

the section is written from these pages

Primary key, indexes and projections

In ClickHouse, the primary key is a sparse index over data sorted by the sorting key: one mark per granule of 8192 rows. Build the key from the columns most often used in query filters; for conditions outside the key there are data skipping indexes and projections.

How the sparse index works

The data of each part is written in sorting key order and split into granules — blocks of 8192 rows; their size is set by the index_granularity setting. The primary index of a part stores one mark per granule — the first key value in it. The index is small and fits entirely in memory, and lookups on the first key column use a binary search over the marks. A query reads only the granules that may contain the values it needs — it never addresses individual rows.

The value 42 may also sit at the end of granule 4, so both neighbouring granules are read.

The index points to granules, not to rows: even a point lookup reads a whole granule. If the value being looked up matches a mark, the previous granule is read as well — its rows may end with that value. How parts and their background merges work is covered in the section “Table engines: MergeTree and its family”.

How to choose key columns

Put into the key the columns that appear most often in WHERE conditions and cut away the most data; 4–5 columns are usually enough. Columns with low cardinality — the number of distinct values — come first. On the first key column the index uses a binary search; the remaining columns use a generalised exclusion algorithm, which works the better the fewer distinct values the preceding column has. Columns that correlate with the data as a whole also improve compression.

sql
# most queries filter by status and dateCREATE TABLE orders(    order_date Date,    status LowCardinality(String),    customer_id UInt64,    amount Decimal(12, 4))ENGINE = MergeTreeORDER BY (status, order_date, customer_id);

By default, the primary key coincides with the sorting key. An explicit PRIMARY KEY is set as a prefix of ORDER BY: the index becomes shorter while the data stays sorted by all key columns. This is useful when a long key is needed for sorting and merges, but the index only needs the first columns.

sql
# shorter index: only the first two columnsCREATE TABLE orders_short(    order_date Date,    status LowCardinality(String),    customer_id UInt64,    amount Decimal(12, 4))ENGINE = MergeTreePRIMARY KEY (status, order_date)ORDER BY (status, order_date, customer_id);

How many granules a query reads

Check the choice of key with EXPLAIN indexes = 1: the Indexes section of the read step shows how many parts and granules remain after pruning. Granules: 18/1024 means “selected out of the total”; if there is no Indexes section at all, the query reads the whole table. From version 25.9 the output is incomplete unless the settings use_query_condition_cache = 0 and use_skip_indexes_on_data_read = 0 are set. For a walkthrough of the full plan, see the section “Performance and query diagnostics”.

sqlin clickhouse-client
EXPLAIN indexes = 1SELECT count()FROM ordersWHERE status = 'paid'  AND order_date >= '2026-01-01'SETTINGS use_query_condition_cache = 0,         use_skip_indexes_on_data_read = 0;
textexample output
ReadFromMergeTree (orders)Indexes:  PrimaryKey    Keys:      status      order_date    Condition: and((status in ['paid', 'paid']), ...    Parts: 6/6    Granules: 18/1024

Data skipping indexes

For conditions on columns outside the key there are data skipping indexes, also available only in the MergeTree family. A block of such an index covers GRANULARITY granules, and a summary is stored for each block: minimum and maximum, a set of values or a bloom filter. If the condition cannot hold within a block, ClickHouse skips it without reading the granules.

sql
# lookup on a column outside the sorting keyALTER TABLE ordersADD INDEX idx_customer customer_id TYPE bloom_filter GRANULARITY 4; # build it for already inserted data tooALTER TABLE ordersMATERIALIZE INDEX idx_customer;
TypeConditions it serves
minmaxRanges and comparisons: <, >=, BETWEEN; columns roughly ordered by value
set(N)Equality and IN; few distinct values inside a block and many across the table as a whole
bloom_filterEquality and IN on rare, high-cardinality values; arrays, Map keys and values
textFull-text search: hasAnyToken, hasAllTokens and other text functions
ngrambf_v1Substrings and LIKE on strings; deprecated, superseded by the text index

A skipping index prunes blocks, not rows: if a value occurs in a block even once, the whole block is read. It therefore helps when the column values correlate with the sorting key and cluster in neighbouring granules. The index performs worst in these cases:

  • Values are scattered across the table and do not correlate with the sorting key: the condition matches almost every block.
  • The condition covers a large share of blocks: evaluating the summary only slows the query down.
  • The condition is a range but the type cannot work with ranges: set and bloom filters are not ordered.
  • The index was created after the data was inserted and has not been materialised: it has no effect on existing parts.

Projections

A projection is a hidden table inside the main one, with its own sort order and its own primary index, or with pre-aggregation. On insert, ClickHouse maintains it automatically and picks it for a query by itself whenever the projection would produce the same result more cheaply. Projection usage is shown by EXPLAIN projections = 1.

sql
# projection: its own sort order for filters by customerALTER TABLE ordersADD PROJECTION prj_customer(    SELECT *    ORDER BY customer_id, order_date); ALTER TABLE ordersMATERIALIZE PROJECTION prj_customerSETTINGS mutations_sync = 1;

Instead of SELECT *, a projection is written as an aggregate with GROUP BY — ready-made aggregates are computed right at insert time. The price is double writing and extra disk space; a projection definition has no WHERE or JOIN, and on tables with projections lightweight deletes DELETE FROM do not work by default (the behaviour is set by the lightweight_mutation_projection_mode setting). For complex aggregation, materialized views are more flexible — see the section “Materialized views”.

Section sources

the section is written from these pages

Inserts and data modification

ClickHouse is designed for rare, large inserts: every insert creates a new part on disk, so data is batched before it is sent. Changing a row here means a new insert, not an UPDATE. The documentation recommends batches of 1,000 rows, ideally 10,000–100,000, and about one insert per second.

Batch inserts

Every insert carries an unavoidable overhead, whatever the batch size. The server parses the data, sorts it by the sorting key, builds the index and writes a separate part to disk. Small, frequent inserts multiply tiny parts: background merges cannot keep up with compacting them, the load on the disk grows, and in the end the too many parts error appears. How parts and their merges work is covered in the section “Table engines: MergeTree and its family”.

The data is buffered on the application side and sent in a single request. It helps to sort the batch by the sorting key in advance — the server will skip its own sorting, but this is an optional optimisation. A batch spread across many partitions slows the insert down: before sending, group the data by the partition key.

basha large batch in a single request
# the application buffer is flushed with a single requestclickhouse-client --query "INSERT INTO events FORMAT JSONEachRow" \  < batch.jsonl

Formats and data ingestion

ClickHouse reads more than 70 input formats. Applications usually send the binary Native: by default the Go and Python clients send it, and there is almost nothing left for the server to parse. For loading files and for integrations, CSV, TSVWithNames, JSONEachRow and Parquet are convenient. The format is specified explicitly: the data follows FORMAT, and SETTINGS comes before it. The Values format of INSERT … VALUES allows expressions in values, but executes them inefficiently.

sqldata straight in the query
INSERT INTO eventsFORMAT JSONEachRow{"event_date":"2026-11-06","user_id":1,"url":"/"}{"event_date":"2026-11-06","user_id":2,"url":"/docs"}

Local files are read by the file() table function, object stores by s3(). An INSERT … SELECT FROM s3() query reads the data as a stream, without holding the whole file in memory. A file on the client side is inserted with INSERT … FROM INFILE — the format is also specified in FORMAT.

sqlloading Parquet from a bucket
INSERT INTO eventsSELECT event_date, user_id, urlFROM s3(  'https://datasets.example.com/events/*.parquet',  NOSIGN,  'Parquet');

Asynchronous inserts

When a batch cannot be assembled on the client — hundreds of agents or services each send a single row — batching is moved to the server. The async_insert setting stacks queries into a buffer and writes the data to disk when the first of these conditions is met:

  • the buffer reaches 100 MiB (async_insert_max_data_size);
  • the async_insert_busy_timeout_ms timeout expires — 200 ms by default, adaptive since version 24.2;
  • 450 queries have accumulated (async_insert_max_query_number).
sqlthe mode for a single query
INSERT INTO eventsSETTINGS async_insert = 1, wait_for_async_insert = 1VALUES ('2026-11-06 10:00:00', 1, '/docs');

Until the buffer is flushed, the data in the queries is not visible. By default wait_for_async_insert = 1: the server confirms the insert only after the buffer is flushed, so an error still reaches the client. A value of 0 is a “fire and forget” mode: minimal latency, but errors surface only in the server log and in the system.asynchronous_inserts table. Data is lost if the buffer fails. Parsing happens at flush time: if even one row of a query cannot be parsed, the buffer rejects that entire query. Before maintenance or a server shutdown, the accumulated buffers are flushed with the SYSTEM FLUSH ASYNC INSERT QUEUE command. Even with async_insert the risk of the too many parts error remains: with a high-cardinality partition key, each flush creates a part for every key value in the buffer.

Retrying an insert after a failure

An insert may go through while its acknowledgement never reaches the client — because of a network interruption or a timeout. Retrying such a query is safe: identical batches are deduplicated, and the retry is silently skipped. There is one condition — the batch must repeat byte for byte: the same content and the same row order, without re-sorting.

Non-deterministic expressions break the retry: now() or generateUUIDv4() in a default value make every batch unique, and deduplication will not recognise it. For such cases there is the insert_deduplication_token setting. Deduplication itself is enabled by the deduplicate_insert setting by default and works wherever the block log is kept: ReplicatedMergeTree always has it, while plain MergeTree needs a positive non_replicated_deduplication_window. Since version 26.2, deduplication also covers asynchronous inserts — a retried query does not discard the other queries from the same buffer.

Modification and deletion

ALTER TABLE … UPDATE and ALTER TABLE … DELETE are mutations: asynchronous background operations. They do not edit rows in place but rewrite the whole parts affected by the change. Editing a single row can rewrite gigabytes. Mutations do not block inserts, but on one table they line up in strict order and are applied to each part in turn, and a reader may see a mixture of old and new parts during a mutation. They are used for one-off bulk fixes, not for regular updates.

sqla one-off bulk edit
ALTER TABLE eventsUPDATE url = '/new-path'WHERE url = '/old-path';

Lightweight deletion, DELETE FROM, is also a mutation but a cheaper one: it marks rows as deleted instead of rewriting them. It is available only to the MergeTree family. By default DELETE responds only once the rows are marked; physically they disappear at the next merge, and until then queries filter out the marked rows. A large range is cheaper to drop whole, together with its partition: ALTER TABLE … DROP PARTITION marks its parts inactive and erases the data outright, without rewriting rows.

MethodCostWhen to use it
a new insert into ReplacingMergeTreean ordinary insert; versions collapse during mergesregular “updates” of an object’s state, upsert
DELETE FROMa lightweight mutation: marks rows, deletes them at a mergerare point deletions
ALTER TABLE … UPDATE / DELETErewriting whole parts, noticeable I/Oone-off bulk fixes
ALTER TABLE … DROP PARTITIONmarks the partition’s parts inactive and erases them outrighttime-based rotation, deleting a large range

If rows need to be “updated” regularly, insert a new version of the row and pick the current one with a query. How ReplacingMergeTree works and how it differs from CollapsingMergeTree is covered in the section “Table engines: MergeTree and its family”.

Section sources

the section is written from these pages

Materialized views

A materialized view in ClickHouse is a trigger on insert: for every inserted block it runs its own SELECT and writes the result into the target table. Report computation moves from read time to insert time; for JOINs and the full picture a refreshable view is used.

An insert into the source table goes through the view query: every inserted block is transformed, and the result goes into the target table — the one named in the TO clause. New results are added alongside the old ones and are merged by background part merges, so the summary over all data equals what a GROUP BY over the source table would give. The target table is usually many times smaller than the source, so reports over it read quickly. Several views can be chained into a cascade: the target table of one view serves as the source for the next, and an insert fires at every step of the pipeline.

The aggregate is computed at insert; parts of the target table are merged in the background.
sqlsource table, target table and the view
CREATE TABLE events (    ts DateTime,    user_id UInt64,    duration_ms UInt32)ENGINE = MergeTreeORDER BY (ts, user_id); CREATE TABLE events_daily (    day Date,    requests SimpleAggregateFunction(sum, UInt64),    total_ms SimpleAggregateFunction(sum, UInt64))ENGINE = AggregatingMergeTreeORDER BY day; CREATE MATERIALIZED VIEW events_daily_mv TO events_daily ASSELECT    toDate(ts) AS day,    count() AS requests,    sum(duration_ms) AS total_msFROM eventsGROUP BY day;
sqlreport over the target table
SELECT    day,    sum(requests) AS requests,    sum(total_ms) / sum(requests) AS avg_msFROM events_dailyWHERE day >= today() - 7GROUP BY dayORDER BY day;

The target engine and aggregate states

For simple sums and counts, SummingMergeTree is enough for the target table: during a merge it adds up the numeric columns of rows with the same key. An average, a quantile or a count of distinct values needs AggregatingMergeTree: at insert the aggregate is finalised with the -State combinator (avgState, quantileState), the column gets the AggregateFunction type, and on read the states are merged further with the -Merge combinator. The summary can also be read with FINAL, but grouping by the key is usually more efficient.

sqlan average via the aggregate state
CREATE TABLE sessions_daily (    day Date,    avg_state AggregateFunction(avg, UInt32))ENGINE = AggregatingMergeTreeORDER BY day; CREATE MATERIALIZED VIEW sessions_daily_mv TO sessions_daily ASSELECT    toDate(start) AS day,    avgState(duration_ms) AS avg_stateFROM sessionsGROUP BY day;
sqlreading the state
SELECT day, avgMerge(avg_state) AS avg_msFROM sessions_dailyGROUP BY day;

Backfilling past data

The view sees only blocks inserted after it was created; existing rows of the source never reach the target table. History is backfilled with the POPULATE keyword at creation — existing data is pushed through the view query — or by a separate insert of the query result into the target table. POPULATE cannot be combined with REFRESH, and Replicated databases do not support it.

sqlbackfilling the target table with history
INSERT INTO events_dailySELECT    toDate(ts) AS day,    count() AS requests,    sum(duration_ms) AS total_msFROM eventsGROUP BY day;

Refreshable views

Not every schema suits an incremental view with a JOIN: only an insert into the leftmost table of the query fires it, the right-hand tables are read in full, and changes to them go unnoticed by the summary. A refreshable materialized view runs the query over all data on a schedule and replaces the whole contents of the target table. The interval is set by REFRESH EVERY, appending instead of replacing — APPEND, a dependency on another view — DEPENDS ON.

sqla full hourly rebuild of the data mart
CREATE MATERIALIZED VIEW sales_enriched_mvREFRESH EVERY 1 HOUR TO sales_enriched ASSELECT    s.id,    s.amount,    u.name AS user_nameFROM sales AS sLEFT JOIN users AS u ON u.id = s.user_id;
sqlthe state of refreshes in system.view_refreshes
SELECT view, status, last_success_time, next_refresh_timeFROM system.view_refreshes;

A view or a projection

A projection is a hidden copy of a table’s data with a different row order or an aggregate; the optimiser substitutes it into the query on its own. It is covered in detail in the section “Primary key, indexes and projections”.

FeatureMaterialized viewProjection
Where the result livesa separate target tableinside the source table
How it is readby querying the target tableautomatically, by the optimiser
JOIN and WHERE in the definitionyesno
Chains of viewsyesno
Source engineany, the target is MergeTreeMergeTree only

Choose a view when aggregates from one or several tables need to be brought together into a separate data mart, filtered at insert, or assembled into a multi-step pipeline. A projection saves the day when queries filter on columns outside the primary key and the key cannot be changed.

Section sources

the section is written from these pages

Replication, shards and Keeper

A replica stores a copy of the data, a shard is a subset of the data, and ClickHouse Keeper keeps replicas consistent across servers. Fault tolerance comes from ReplicatedMergeTree replicas, the sharding key spreads data across servers, and the Distributed table accepts inserts and queries and dispatches them across the cluster.

Cluster, shard and replica

A replica is a copy of the data; the original counts as a replica too, so there is always at least one, and a second one already provides fault tolerance. A shard is a subset of the data: as long as data is not split between servers, the whole dataset lives in a single shard. A cluster is a set of shards and replicas described in the remote_servers section of the configuration; the cluster composition is visible in system.clusters.

A typical cluster is 2 shards with 2 replicas each: replicas survive a server failure, shards share the write and read load.

Distributed accepts an insert and fans it out across the shards; Keeper keeps the replicas in sync.

ReplicatedMergeTree and the Keeper path

Replication works at the table level and is independent of sharding: each shard has its own independent replication. Replicated tables are MergeTree variants with the Replicated prefix; each of them needs a path in Keeper. The path uses the {shard} and {replica} macros substituted from the server configuration: paths differ between shards thanks to {shard}, while replicas of the same shard differ only in {replica}.

xmlconfig.xml of the first replica
<macros>    <shard>01</shard>    <replica>ch1</replica></macros>
sqlon every server of the cluster
CREATE TABLE analytics.events ON CLUSTER main(    event_date Date,    event_id UInt64)ENGINE = ReplicatedMergeTree(    '/clickhouse/tables/{shard}/{database}/{table}',    '{replica}')ORDER BY (event_date, event_id);

Replicas are equal peers: any of them accepts INSERT and ALTER, the data lands on whichever server received the request and then spreads to the rest asynchronously. Each inserted block produces about 10 entries in Keeper, so insert in large batches — roughly no more than 1 INSERT per second per table. Data blocks are deduplicated: if the client does not know whether an insert went through, it is safe to repeat it.

ClickHouse Keeper

Keeper stores replica metadata and the queue of distributed DDL queries: both replication and ON CLUSTER rely on it. It is written in C++ and runs the RAFT algorithm: writes are linearised, a quorum requires a majority of the nodes, so a 3-node ensemble survives the failure of one. Over the client protocol Keeper is compatible with ZooKeeper: ZooKeeper 3.4.5 or newer works for replication, but Keeper is the recommended option. A mixed ensemble of Keeper and ZooKeeper cannot be assembled, and clickhouse-keeper-converter migrates ZooKeeper data. Keeper runs either as a separate clickhouse-keeper process or inside the ClickHouse server.

xmlconfig of the keeper1 node
<keeper_server>    <tcp_port>2181</tcp_port>    <server_id>1</server_id>    <log_storage_path>/var/lib/clickhouse/keeper/log</log_storage_path>    <snapshot_storage_path>/var/lib/clickhouse/keeper/snapshots</snapshot_storage_path>    <raft_configuration>        <server>            <id>1</id>            <hostname>keeper1</hostname>            <port>9234</port>        </server>        <server>            <id>2</id>            <hostname>keeper2</hostname>            <port>9234</port>        </server>        <server>            <id>3</id>            <hostname>keeper3</hostname>            <port>9234</port>        </server>    </raft_configuration></keeper_server>

Clients connect to the tcp_port port (2181 by default), and ensemble nodes talk to each other on the port from raft_configuration — 9234 in the documentation examples. Each node has its own server_id, the same in the ensemble and in the node configuration.

Distributed and shards

The Distributed table stores no data itself — it is a route across the cluster: the engine takes the cluster name, the database and the name of the local table. A SELECT goes to all shards, reading is parallelised automatically, and the indexes of the remote servers are used. The sharding key is an expression that decides which shard a row lands on when inserting through Distributed: rand() distributes data randomly, while sharding by UserID keeps one user’s data on one shard and simplifies IN and JOIN.

xmlconfig.xml, the main cluster
<remote_servers>    <main>        <shard>            <internal_replication>true</internal_replication>            <replica>                <host>ch1</host>                <port>9000</port>            </replica>            <replica>                <host>ch2</host>                <port>9000</port>            </replica>        </shard>        <shard>            <internal_replication>true</internal_replication>            <replica>                <host>ch3</host>                <port>9000</port>            </replica>            <replica>                <host>ch4</host>                <port>9000</port>            </replica>        </shard>    </main></remote_servers>
sqlon top of the local tables
CREATE TABLE analytics.events_all ON CLUSTER main(    event_date Date,    event_id UInt64)ENGINE = Distributed(main, 'analytics', 'events', rand());
MethodHow it worksWhen to use it
Insert into DistributedThe sharding key picks the shard, the table distributes the data itselfA single entry point for the application
Insert into the local tablesThe client decides itself which shard to write to; Distributed is only needed for readsYour own placement algorithm, maximum control

Enable internal_replication when the local tables are replicated: one live replica of the shard receives the write, and ReplicatedMergeTree itself keeps them in sync from then on. Without it, Distributed writes to every replica itself and never checks their consistency — over time the replicas’ data drifts apart.

CREATE, DROP and ALTER queries with ON CLUSTER run on all servers of the cluster at once; their queue lives in Keeper. With an explicit path and replica name, without macros, ON CLUSTER queries do not work, which is why the ReplicatedMergeTree parameters are given as substitutions.

Order of building the cluster

  1. Bring up a 3-node Keeper ensemble.
  2. List the Keeper addresses in the zookeeper section on every ClickHouse server.
  3. Describe the shards and replicas in remote_servers.
  4. Create the local ReplicatedMergeTree table with a single ON CLUSTER query.
  5. On top of it, create the Distributed table and insert into that.

Section sources

the section is written from these pages

Backup and restore

Backups are made with the BACKUP command: it saves a table, a database or the whole server to local disk or S3, and RESTORE brings the data back from the copy. There is no built-in scheduling: an external scheduler such as cron takes the backups.

How to take a backup

What to specify in the commandExampleWhen to use it
A single tableBACKUP TABLE logs TO Disk('backups', 'f.zip')A backup after a risky mutation
A whole databaseBACKUP DATABASE logs …Before upgrading applications
The whole serverBACKUP ALLA migration or a regular full backup
sqlclickhouse-client
BACKUP TABLE logs TO Disk('backups', 'logs.zip')SETTINGS compression_method='lzma', compression_level=3

The destination is set with Disk — a reference to a disk from the configuration — or S3 with the bucket address and keys. The ASYNC flag runs the backup in the background: the command immediately returns the id and status of the operation.

sqlbackup to S3 without a disk in the configuration
BACKUP TABLE logsTO S3('https://example.com/backups/', 'key', 'secret')ASYNC

Progress and the result are visible in system.backups: if a backup fails, an error column appears there too. Taking the backup again under the same name produces the BACKUP_ALREADY_EXISTS error.

Where backups are stored: the backups disk

The name inside Disk is a disk from the storage configuration. It does not exist by default, so the backup_disk.xml file in config.d declares a disk named backups and allows it for backups.

xml/etc/clickhouse-server/config.d/backup_disk.xml
<clickhouse>    <storage_configuration>        <disks>            <backups>                <type>local</type>                <path>/backups/</path>            </backups>        </disks>    </storage_configuration>    <backups>        <allowed_disk>backups</allowed_disk>        <allowed_path>/backups/</allowed_path>    </backups></clickhouse>

The backups disk is set aside for backups only: MergeTree tables are not placed on it. The path in allowed_path restricts where the command is allowed to write.

Incremental backups

An incremental backup keeps only the changes since the base backup — the first full backup, set by the base_backup setting. Several incrementals can be taken from one base; when restoring, only the latest one is specified.

sqlcron: full backup weekly, incremental daily
-- base backup, duplicated once a weekBACKUP TABLE logs TO Disk('backups', 'base.zip'); -- incremental: only the changes since base.zipBACKUP TABLE logsTO Disk('backups', 'monday.zip')SETTINGS base_backup = Disk('backups', 'base.zip');

The base backup is kept for as long as its incrementals exist: without it, an incremental cannot be restored.

Restore

RESTORE accepts the same objects and destinations as BACKUP. By default, data is not restored into a non-empty table — the allow_non_empty_tables=true setting is needed, but it mixes the data from the backup into the existing data.

sql
-- into a new table, the old one stays untouchedRESTORE TABLE logs AS logs_restoredFROM Disk('backups', 'logs.zip'); -- restore on top, if the table is no longer emptyRESTORE TABLE logs FROM Disk('backups', 'logs.zip')SETTINGS allow_non_empty_tables=true;

Other methods

Besides BACKUP and RESTORE, the data can also be saved in other ways:

  • ALTER TABLE ... FREEZE PARTITION makes a copy of a partition as hard links in the shadow directory, so it takes up almost no space; the copy is moved to another medium and brought back with the ALTER TABLE ... ATTACH PARTITION command.
  • A filesystem snapshot, for example ZFS, on a separate replica excluded from queries.
  • A second subscription to the input stream, for example from Kafka, also stores the data in cold storage.

FREEZE can be automated with the clickhouse-backup tool.

Section sources

the section is written from these pages

Query performance and diagnostics

A slow query in ClickHouse almost always reads more than it needs: too many rows or columns that are too wide. Start the search with the system.query_log — it shows which queries are the heaviest — and continue with the EXPLAIN plan. After each change, compare read_rows, read_bytes and duration with a repeated run.

Find the heavy queries

Every finished query lands in system.query_log with its duration, the number of rows and bytes read and the memory usage. The data is flushed to the table periodically, so the latest queries appear after SYSTEM FLUSH LOGS. Look for recurring patterns rather than a one-off failure: normalized_query_hash is the same for queries that differ only in literal values.

sqlclickhouse-client
SELECT    normalized_query_hash,    count() AS executions,    quantile(0.5)(query_duration_ms) AS median_ms,    max(query_duration_ms) AS max_ms,    formatReadableSize(avg(read_bytes)) AS avg_read_bytes,    formatReadableSize(max(memory_usage)) AS max_memoryFROM system.query_logWHERE event_time >= now() - INTERVAL 1 DAY  AND type = 'QueryFinish'  AND is_initial_query = 1  AND query_kind = 'Select'GROUP BY normalized_query_hashHAVING executions >= 2ORDER BY median_ms DESCLIMIT 10

The filter type = 'QueryFinish' keeps finished queries, and is_initial_query = 1 keeps only top-level queries, without the child queries of distributed execution. On a cluster the log is local to each node, so such queries are wrapped in clusterAllReplicas.

ColumnWhat it shows
query_duration_msQuery execution time in ms
read_rowsRows read by all tables of the query, including subqueries
read_bytesUncompressed bytes read by all tables of the query
memory_usageMemory consumed by the query
normalized_query_hashThe same for queries that differ only in literals

Read the plan

EXPLAIN shows the query plan without running it: the tree of steps from reading the table to the result. The EXPLAIN indexes = 1 variant adds an Indexes section to the read step: which indexes matched and how many parts and granules remain after each one. Since version 25.9, meaningful output requires the settings use_query_condition_cache = 0 and use_skip_indexes_on_data_read = 0.

sqlin clickhouse-client
EXPLAIN indexes = 1SELECT pickup_datetime, total_amountFROM tripsWHERE pickup_datetime >= '2026-01-01'  AND pickup_datetime < '2026-02-01'SETTINGS use_query_condition_cache = 0,         use_skip_indexes_on_data_read = 0
textexample output
ReadFromMergeTree (trips)Indexes:  PrimaryKey    Keys:      pickup_datetime    Condition: and((pickup_datetime in ...    Parts: 9/9    Granules: 5061/40167...

Here Parts and Granules are written as “after the index / before”: the sorting key left 5,061 granules out of 40,167. If the read step has no Indexes section at all and read_rows in the log equals the number of rows in the table, the query is reading it in full. EXPLAIN ANALYZE runs the query, discards the result and adds actual numbers per step to the plan; such a run counts against quotas and limits like an ordinary query. EXPLAIN PIPELINE shows the processing pipeline: the stages, the copies of processors in a parallel step such as AggregatingTransform × 2, and the stream merges.

Read less data

ClickHouse reads from disk only the columns named in the query, so the first step towards speed is not reading what you do not need. List columns instead of SELECT * and avoid wide types: LowCardinality for strings with repeats, the narrowest numeric type, and Nullable only where the difference between NULL and the default value matters. The saving is visible in read_bytes.

Filtering rows also saves reads: PREWHERE first reads only the columns of the condition, and the rest only for blocks where the condition found matches. ClickHouse moves suitable conditions from WHERE to PREWHERE on its own (optimize_move_to_prewhere is enabled by default), so writing PREWHERE explicitly is usually unnecessary.

Joins and denormalisation

A join costs more than reading one table: denormalisation moves this work from query time to insert time or preprocessing. A join is worth removing when the tables change rarely and the related columns are known in advance; instead of duplicating lookup tables, compute aggregates with materialized views — see the section “Materialized views”.

When a join is needed, put the smaller table on the right: the default join is a hash join, and ClickHouse builds the hash table from the right side. The join_algorithm setting chooses the algorithm, with the default value direct,hash,ie_join: the first applicable one is used. Dictionaries offer the direct join direct — for a LEFT ANY JOIN this is often the fastest path. If the right-hand table does not fit in memory, the data spills to disk: the threshold is set by max_bytes_ratio_before_external_join, by default 0.5 of available memory.

The FINAL modifier is a different matter: it merges the data further at query time so that ReplacingMergeTree and related engines return a result without duplicates. Such a query is slower and may read key columns even when they are not in the SELECT list. Write FINAL only where the result is wrong without it, and filter by primary key columns.

Query limits

SettingWhat it limitsDefault
max_memory_usageMemory of one query on one server0 — no limit
max_threadsProcessing threads of one queryNumber of CPU cores
max_execution_timeQuery execution time, s0 — no limit

A limit is set surgically: in the SETTINGS after the query, for the session with the SET command, or in a user profile. A value of 0 limits nothing, so a single heavy query can take all the memory of the server. SHOW PROCESSLIST shows the memory of running queries. Execution time is checked at separate points of the pipeline, so the actual duration can exceed max_execution_time; once it is exceeded, the query is interrupted with an error — timeout_overflow_mode with the default value throw is responsible for that.

Further along the chain: how to choose the sorting key and data skipping indexes — see the section “Primary key, indexes and projections”; how to avoid repeated computation — see the section “Materialized views”; a rundown of error messages and interrupted queries — see the section “Common errors and troubleshooting”.

Section sources

the section is written from these pages

Security

There are two main threats: the default user has full permissions and an empty password (users.xml allows any address for it, ::/0), and ports 9000 and 8123 are all too easy to open to the whole network via listen_host — and the server ends up on the internet (in a container the ports already listen on all addresses). Without listen_host the server listens only on 127.0.0.1 and ::1. Set a password for default, give each application its own account with a role, and have the ports listen only on 127.0.0.1 unless the server needs to be reachable over the network.

Users and roles via SQL

ClickHouse stores accounts, roles, settings profiles and quotas as objects and manages them with SQL commands: CREATE USER, CREATE ROLE, GRANT, REVOKE. The alternative is the users.xml and config.xml files, but the SQL approach is the officially recommended one. For the commands to work, at least one user needs the access_management=1 setting enabled: in the stock installation it is already enabled for default in users.xml. For the full set of permissions — so that GRANT ALL … WITH GRANT OPTION works — also uncomment show_named_collections_secrets=1 in users.xml: without it default has an incomplete set of privileges and the query will be rejected.

The first step is to create an administrator with SQL permissions — it then manages the remaining accounts through clickhouse-client. After that, the documentation advises limiting the permissions of default and disabling access_management for it.

sqlin `clickhouse-client` as `default`
CREATE USER admin IDENTIFIED BY 'change-me';GRANT ALL ON *.* TO admin WITH GRANT OPTION;

The server hashes the password itself: IDENTIFIED BY takes the type from the default_password_type setting, which defaults to IDENTIFIED WITH sha256_password BY. A plaintext password (plaintext_password) is not used: it would be stored as plain text in a file under /var/lib/clickhouse/access. Privileges are collected into a role with the GRANT command, and the role is granted to a user with GRANT … TO. Permissions on a database with a wildcard (analytics.*) also cover tables created later, and ALTER USER changes the password without recreating the account.

sqlas the administrator
CREATE ROLE readonly;GRANT SELECT ON analytics.* TO readonly;CREATE USER alice  IDENTIFIED WITH sha256_password BY 'change-me'  HOST IP '192.168.10.0/24';GRANT readonly TO alice;SET DEFAULT ROLE readonly TO alice;

After this alice can read the data of the analytics schema and nothing else — no inserts, no modifications. SET DEFAULT ROLE makes the role active on login; without it the role has to be enabled with the SET ROLE command. SHOW GRANTS FOR alice shows the permissions of the user and of its roles; SHOW ACCESS shows all access objects at once.

Ports and listen_host

The server listens on several ports; which of them to leave open depends on what the client uses. The values live in config.xml, and the easiest way to override them is with a file in the /etc/clickhouse-server/config.d/ directory.

PortUsed forOpen to the outside
8123HTTP interfaceno, behind a reverse proxy
8443HTTP with TLSyes, if there is no proxy
9000the native protocolno, own network only
9440the native protocol with TLSyes
9004MySQL emulationno
9005PostgreSQL emulationno
9009interserver communicationno
9010interserver communication with TLSno, cluster nodes
9181ClickHouse Keeperno, cluster nodes

The listen_host setting decides on which addresses the server keeps its ports open. The values 127.0.0.1 and ::1 leave access only from the server itself; :: listens on all interfaces and is needed when a client reaches the server over the network, or when cluster nodes talk to each other. Check what the server is listening on with ss -tlnp, and block the unneeded ports with a firewall; the rules are described in the Linux server hardening reference.

xmlconfig.d/listen.xml
<listen_host>127.0.0.1</listen_host><listen_host>::1</listen_host>

The wrong way and the right way

The users.xml below is a typical outcome: a default user with no password, addresses allowed for everyone (::/0 — the whole internet), and data writing allowed (readonly=0). In the correct setup the application has a separate account with minimal permissions and the address of its own subnet.

xmlthe wrong way
<clickhouse>    <profiles>        <default><readonly>0</readonly></default>    </profiles>    <users>        <default>            <password></password>            <networks>                <ip>::/0</ip>            </networks>        </default>    </users></clickhouse>
sqlthe right way
CREATE USER app  IDENTIFIED BY 'change-me'  HOST IP '10.0.5.0/24';GRANT SELECT, INSERT ON events.* TO app;

TLS for clients and between nodes

Encryption is enabled in the server configuration: the openSSL section specifies the certificate and key, and https_port (8443) and tcp_port_secure (9440) replace the plaintext 8123 and 9000. For cluster node communication enable interserver_https_port (9010) and mark the connections in remote_servers with <secure>1</secure>.

xmlconfig.d/tls.xml
<openSSL>  <server>    <certificateFile>/etc/clickhouse-server/certs/ch1.crt</certificateFile>    <privateKeyFile>/etc/clickhouse-server/certs/ch1.key</privateKeyFile>    <caConfig>/etc/clickhouse-server/certs/ca.crt</caConfig>    <disableProtocols>sslv2,sslv3</disableProtocols>    <preferServerCiphers>true</preferServerCiphers>  </server></openSSL><https_port>8443</https_port><tcp_port_secure>9440</tcp_port_secure><interserver_https_port>9010</interserver_https_port>

The client connects to the secure port with the --secure flag: clickhouse-client --host ch1.example.com --port 9440 --secure. How to issue and sign certificates — the TLS and PKI reference, the section “X.509 certificates”.

Settings profiles, quotas and limits

A separate account protects the data, but not the server: a single heavy SELECT can eat all the memory. Limits on queries are set by three mechanisms: a settings profile limits each query, a quota counts usage per hour or per day, and the readonly setting forbids changing data and settings. Almost all limits apply only to SELECT, and a distributed query is checked on each server separately.

sqla profile with a memory limit
CREATE SETTINGS PROFILE analytics_ro  SETTINGS readonly = 1,    max_memory_usage = 10000000000 MIN 1000000000 MAX 20000000000  TO alice;
sqlan hourly quota
CREATE QUOTA q_alice FOR INTERVAL 1 hour MAX queries = 1000,  errors = 100 TO alice;

The profile sets a value and hard bounds: the user will not be able to raise max_memory_usage above the upper bound, and readonly=1 will forbid both writing and changing settings with SET. A quota adds a counter per interval; the limit on the number of errors (errors) exposes a script stuck in a loop. A row policy filters the rows of a single table for a role or a user and is created with the CREATE ROW POLICY command; it only makes sense together with readonly=1: whoever can modify the table can bypass the filter.

Further reading

  • LDAP, Kerberos, X.509 certificate and external HTTP authentication — the “External Authenticators” page of the ClickHouse documentation; SSH key authentication — the ssh_key method in CREATE USER.
  • Secure communication between cluster nodes and the Keeper ports — see the section “Replication, shards and Keeper”.
  • Basic host protection and a firewall — the Linux server hardening reference.

Section sources

the section is written from these pages

Common errors and troubleshooting

Start diagnosing from the server log and the system tables: the latest errors are in clickhouse-server.err.log and system.errors, the history of queries with memory usage and the error text is in system.query_log, and the composition of a table is in system.parts.

SymptomWhere to lookWhat to do
Too many parts (code 252)system.partsCheck the partition key and batch your inserts
MEMORY_LIMIT_EXCEEDEDsystem.query_logFind the query and raise or split the limit
Not enough privileges (code 497)SHOW GRANTSGrant the missing privileges with GRANT
The client will not connectlisten_host, ports 9000 and 8123Start the server or fix listen_host
Inserts and ALTER failsystem.replicasCheck the connection to Keeper: the is_readonly column
A mutation hangs for hourssystem.mutationsEstimate its size, then cancel it with KILL MUTATION
Duplicates will not go awaysystem.mergesWait for the merge or add FINAL to the query

Too many parts

The server stores a table as a set of immutable parts: each insert produces a new part, and background merges combine them. Frequent small inserts and a partition key with high cardinality multiply the parts faster than merges keep up, and the server returns the Too many parts error. Keep the cardinality of the partition key within 1,000–10,000 values.

sqlparts by partition
SELECT partition, count(*) AS parts, sum(rows) AS rowsFROM system.partsWHERE active AND database = 'analytics'  AND table = 'events'GROUP BY partitionORDER BY parts DESC;
sqla one-off merge of a partition
OPTIMIZE TABLE analytics.eventsPARTITION 202610 FINAL;

If the error keeps recurring, the insert rhythm or the partition key is at fault: hundreds of small inserts per minute or a partition per hour multiply the parts faster than they can be merged. Make the batches bigger on the application side and group data by the partition key before sending — the batch-insert techniques are collected in the section “Inserts and data modification”.

MEMORY_LIMIT_EXCEEDED

The query exceeded the max_memory_usage memory limit. Find the culprit in system.query_log by the type ExceptionWhileProcessing: for such events the exception column is filled in, and memory_usage shows how much memory the query used.

sqlqueries that failed on memory
SELECT formatReadableSize(memory_usage) AS used,       exceptionFROM system.query_logWHERE type = 'ExceptionWhileProcessing'  AND event_date >= today() - 1ORDER BY memory_usage DESCLIMIT 5;

Set a setting for the session with the SET command or in the user profile. If a query runs out of its limit for grouping or sorting, enable spilling to disk: the data that exceeds the limit goes to disk instead of memory.

sqllimits for the duration of a query
-- memory limit for a single querySET max_memory_usage = 32212254720;-- the threshold after which grouping spills to diskSET max_bytes_before_external_group_by = 21474836480;

If the error appears across different queries and keeps coming back, look at what is occupying memory right now: system.processes shows the current queries with their peak memory usage.

sqlqueries running right now
SELECT query, formatReadableSize(peak_memory_usage) AS peakFROM system.processesORDER BY peak_memory_usage DESCLIMIT 5;

When the server is short of memory to begin with and heavy queries are still needed, the experimental memory overcommit technique helps: when memory runs out, a query waits for it to be released while the server suspends the “most overcommitted” query; if the memory is not released within the allotted time, the waiting query fails with an error.

Not enough privileges

The user lacks the privilege for the operation: the server returns Code: 497. Not enough privileges, and the message lists the missing privileges. The administrator grants them with the GRANT command, and SHOW GRANTS shows the user’s own privileges — compare them with the list from the error. If the administrator’s GRANT is rejected, check their own SHOW GRANTS: you can only grant privileges with the same or narrower scope than the administrator’s own.

sqlthe privileges of the app_reader user
SHOW GRANTS FOR app_reader;GRANT SELECT ON analytics.events TO app_reader;

The client does not connect to the server

clickhouse-client and the drivers connect to port 9000 (the native protocol), the HTTP interface to port 8123. No connection? Check that the clickhouse-server service is running, then look at listen_host in config.xml or a file in config.d: it sets the interfaces the ports listen on. The official Docker image opens all interfaces; on a protected network the ports stay on 127.0.0.1 — see the section “Security”.

bashthe server ports on the host
sudo ss -tlnp | grep -E '9000|8123'

A replica in read-only mode

Replicated tables take their metadata from Keeper. Until the server has established a session with it — the <zookeeper> section is not configured, Keeper is unavailable or restarting — the tables go into read-only mode: SELECT works, while inserts and ALTER are rejected. The state is visible in system.replicas: the is_readonly column is 1, and zookeeper_exception holds the last session error. Once the connection is restored, the replica catches up with the others; how replication works is covered in the section “Replication, shards and Keeper”.

sqlreplicas in read-only mode
SELECT database, table, is_readonly, zookeeper_exceptionFROM system.replicasWHERE is_readonly = 1;

A mutation does not finish

Mutations run in the background: ALTER TABLE ... UPDATE returns control immediately, while the command itself can run for hours and take up server resources. The mutation queue is in system.mutations: until a mutation finishes, is_done is 0, and parts_to_do shows how many parts still need rebuilding. A hanging mutation is cancelled with the KILL MUTATION command; this does not damage the data — a mutation rewrites parts rather than changing them in place. Frequent mutations are best avoided altogether: for alternatives, see the section “Inserts and data modification”.

sqlunfinished mutations
SELECT command, create_time, parts_to_doFROM system.mutationsWHERE is_done = 0;
sqlcancel a hanging mutation
KILL MUTATION  WHERE database = 'analytics' AND table = 'events';

Data is not deduplicated in ReplacingMergeTree

The ReplacingMergeTree engine removes duplicates not at insert time but during a background merge, at an unpredictable moment: right after an insert a query will return them again. Deduplication works only within one partition, so compare rows with the same partition key value. Wait for the merge or add the FINAL modifier to the query — it applies merges on the fly; the engine is covered in the section “Table engines: MergeTree and its family”.

sqlcurrent merges
SELECT table, elapsed, round(progress * 100) AS doneFROM system.merges;

Section sources

the section is written from these pages

Versions and what’s new

This reference covers the current stable branch, ClickHouse 26.10; the latest release is 26.10.3.7-stable of 30 October 2026. Stable branches arrive roughly once a month, LTS branches twice a year: in 2026 that is 26.3 and 26.8.

Branches and support

Security fixes go only to the branches listed in the security policy table. Branch 26.7 is already marked there as unsupported, even though its latest releases came out as recently as October.

BranchTypeBranch launchedLatest releaseSupported
26.10stable22 October 202626.10.3.7 — 30 Octoberyes
26.9stable21 September 202626.9.27.3 — 30 Octoberyes
26.8LTS27 August 202626.8.36.3 — 30 Octoberyes
26.7stable22 July 202626.7.37.6 — 22 Octoberno
26.3LTS26 March 202626.3.62.3 — 30 Octoberyes

Choosing a channel: stable brings new features every month, but you have to switch branches often. LTS changes less often and suits upgrades planned in advance. To connect the repository for the channel you need, see the section “Installation and first run”.

What has changed

Below are the changes in the recent branches that affect the topics of this reference. Read the full list of breaking changes in the changelog before every upgrade.

  • Data types and table schema: in 26.9 the Nullable(Tuple(...)) type became generally available and is enabled by default; no setting is needed for it.
  • Data types and table schema: in 26.8 the range of Date32 was extended to [0000-01-01, 9999-12-31], matching DateTime64.
  • Table engines: in 26.10 SELECT ... FINAL from SummingMergeTree no longer removes rows where all summed columns equal zero; background merges and OPTIMIZE TABLE ... FINAL still remove them.
  • Inserting and changing data: in 26.8 max_insert_threads became auto by default instead of 1, and INSERT SELECT now runs in parallel by default.
  • Inserting and changing data: in 26.8 lightweight UPDATE patches received the on-disk format v2.
  • Replication, shards and Keeper: in 26.10 a MergeTree table in an Ordinary database can be turned into ReplicatedMergeTree with the command ATTACH TABLE ... AS REPLICATED.
  • Replication, shards and Keeper: in 26.10, for a Distributed read with skip_unavailable_shards = 1, the error ALL_CONNECTION_TRIES_FAILED is raised when all shards are skipped; previously an empty result was returned.
  • Backup and restore: in 26.9, BACKUP ... TO Disk(...) requires the grant WRITE ON DISK, and RESTORE ... FROM Disk(...) — READ ON DISK.
  • Performance and query diagnostics: in 26.10 system.metric_log by default stores metrics in a single metrics column of type Map instead of thousands of columns.
  • Performance and query diagnostics: in 26.10 sets for IN and workload-limit queries (WORKLOAD) can spill to disk.
  • Security: in 26.10 the server can apply a seccomp system-call filter; in the packages and the Docker image the seccomp setting is trap.

Default compression and the analyzer

In 26.9 the default compression changed from LZ4 to ZSTD(3). For MergeTree columns the choice depends on the part size: LZ4 for parts smaller than 100 MB, ZSTD(3) for the rest. Network traffic always uses ZSTD(3). The price for the smaller volume is a slight increase in CPU load.

The old query analyzer can no longer be disabled: since 26.9 the enable_analyzer setting is deprecated, and in 26.10 a value of 0 is accepted but replaced with 1. In 26.10 the old query parser was removed as well. If the initiator of a distributed query is older than 26.10, the server will still apply the analyzer, and in a mixed cluster the error NOT_FOUND_COLUMN_IN_BLOCK is possible.

sqlcheck the current value
SELECT value FROM system.settings WHERE name = 'compatibility'

Deprecated and removed

  • 26.10: the settings query_plan_read_in_order, query_plan_optimize_prewhere and query_plan_aggregation_in_order are deprecated (now without effect); use optimize_read_in_order, optimize_aggregation_in_order and optimize_move_to_prewhere.
  • 26.10: the zero-argument year() function has been removed — write toYear(today()); the experimental detectTonality function has been removed.
  • 26.10: the settings use_compact_format_in_distributed_parts_names, use_minimalistic_part_header_in_zookeeper and use_minimalistic_checksums_in_zookeeper are deprecated and do nothing.
  • 26.10: for the experimental ZXC codec the block format has changed and old data cannot be read; re-encode the columns before upgrading.
  • 26.9: removed are the CatBoost integration (catboostEvaluate, system.models), the WasmEdge engine for UDFs, the experimental WINDOW VIEW, and the disk options read_resource and write_resource.
  • 26.8: the library dictionary source and the Arrow format implementation based on the Apache Arrow library have been removed.

Security updates

Fixed vulnerabilities are listed by ClickHouse in the security changelog, and the security policy states which branches receive fixes. The latest entry is CVE-2026-116366 of 30 October 2026: under certain conditions an unauthenticated remote user could execute arbitrary code on the server; the fix landed in 26.10.3.7, 26.9.27.3, 26.8.36.3 and 26.3.62.3.

Several changes in 26.10 tighten security and may require permission changes: setting constraints and allow_feature_tier now also apply to users created via SQL; overriding the key of a named collection requires SHOW NAMED COLLECTIONS SECRETS; MySQL connections with ssl_ca verify the certificate chain and the host name. For details, see the section “Security”.

How to upgrade

Compatibility is maintained within a year — two LTS releases: any two versions must work in one cluster if they are less than a year apart. Still, upgrade the cluster members to the same version as quickly as you can: with different versions, distributed queries may slow down and background operations of ReplicatedMergeTree may fail. If the gap is more than a year, upgrade with downtime or through an intermediate version.

  • Keep your settings in /etc/clickhouse-server/config.d/, not in config.xml: that file can be overwritten.
  • Read the breaking changes from your target release down to yours.
  • For each shard, keep some replicas running and upgrade the rest one by one, then swap the groups.
  • Upgrade the servers separately from Keeper (see the section “Replication, shards and Keeper”): Keeper must stay stable for the whole upgrade, and changing it is worth it only for a security fix.
  • Test experimental features on a separate server running the target version first.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “ClickHouse” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61