Showing posts with label clickhouse. Show all posts
Showing posts with label clickhouse. Show all posts

Monday, 7 September 2026

Inside ClickHouse: How MergeTree Tables Store Data on Disk

  

ClickHouse is a high-performance OLAP database designed for fast analytical queries. While developers and data engineers often interact with ClickHouse at a high level like creating tables, inserting data, running analytical queries, it's equally important to understand how ClickHouse organizes and stores that data on disk, especially for performance tuning and debugging.

 

In this post, we’ll explore how data is structured under the hood when using MergeTree tables, the most used table engine in ClickHouse. We’ll also look into the actual files and directories that ClickHouse creates inside its storage path (/var/lib/clickhouse/data).

 

Let’s assume the default ClickHouse data storage path is /var/lib/clickhouse/data. When you navigate to this directory, you’ll see subdirectories representing databases that have been created in your ClickHouse instance.

$ ls -lart /var/lib/clickhouse/data
total 0
drwxr-x---   2 krishna  test   64  4 May 19:05 system
drwxr-x---   3 krishna  test   96  7 May 15:43 archive_db
drwxr-x---   3 krishna  test   96  7 May 19:46 analytics_db
drwxr-x---   5 krishna  test  160 15 May 10:15 default
drwxr-xr-x@ 14 krishna  test  448 19 May 09:38 ..
drwxr-x---   7 krishna  test  224 19 May 17:08 .
drwxr-x---   3 krishna  test   96 19 May 17:08 demo_db

   

Here we can see five databases:

 

·      system (default internal system metadata)

·      archive_db

·      analytics_db

·      default

·      demo_db

 

Each database directory contains subdirectories for its tables. Let’s explore the demo_db database.

 

$ cd demo_db
$ ls
orders          orders_granule_example

   

In this example, the demo_db contains two tables:

·      orders and

·      orders_granule_example.

 

Let’s go one step deeper into orders_granule_example to see how ClickHouse organizes its data files.

 

$ tree orders_granule_example
orders_granule_example
├── all_1_1_0
│   ├── checksums.txt
│   ├── columns_substreams.txt
│   ├── columns.txt
│   ├── count.txt
│   ├── data.bin
│   ├── data.cmrk4
│   ├── default_compression_codec.txt
│   ├── metadata_version.txt
│   ├── primary.cidx
│   └── serialization.json
├── detached
└── format_version.txt

all_1_1_0/

This is a data part directory. In MergeTree, data is written in parts, and these parts are later merged. The name all_1_1_0 indicates:

 

all: the partition (if no partitioning is specified, it's all)

1_1_0: the min block, max block, and level of the part

 

Files inside all_1_1_0/:

·      columns.txt: Lists all columns in the data part.

·      columns_substreams.txt: Metadata about column substreams (used during compression).

·      count.txt: Number of rows in this part.

·      checksums.txt: Contains checksums for all files for integrity verification.

·      data.bin, data.cmrk4: Actual column data and mark files for fast seek. A mark file contains offset pointers (called marks) that allow ClickHouse to quickly locate data inside the corresponding .bin (binary data) files.

·      primary.cidx: Stores values for the primary key index.

·      serialization.json: Information about how columns are serialized.

·      default_compression_codec.txt: Indicates the compression method used.

·      metadata_version.txt: Metadata schema version.

 

detached/

This is a special folder used when parts are detached manually or by the system (for example, for backup or manual inspection). These parts are not currently active in the table but are preserved.

format_version.txt

Contains the format version for the MergeTree table directory.

 

Understanding this storage layout can help you with:

 

·      Debugging: Inspecting files when facing data corruption or merge issues.

·      Backups: Manually copying specific data parts for backup.

·      Performance Tuning: Knowing how many parts exist and how merges work can help optimize performance.

·      Low-Level Exploration: For developer building tools that work with ClickHouse.

 

In summary, ClickHouse’s MergeTree engine is optimized for performance, and part of that optimization comes from how it organizes and stores data on disk. Each table is composed of parts, each part has its own directory and set of files that manage data, indexes, checksums, and more.

 

Exploring the physical file layout of a table can give you insights that help with debugging, maintenance, and system optimization. Next time you're running a query in ClickHouse, remember that a lot is happening behind the scenes.

 

Previous                                                    Next                                                    Home

How ClickHouse Uses Sparse Indexes: A Deep Dive into primary.idx and Granules

  

In ClickHouse, MergeTree tables use sparse primary indexes for fast data access, where as a granule is a logical block of rows within a data part.

 

primary.idx

In ClickHouse, the primary.idx file is part of the sparse primary index used by MergeTree tables. It stores the first row’s primary key value of each granule, enable fast filtering during query execution.

 

index_granularity = N

index_granularity = N means ClickHouse stores an index entry for every N rows. This allows ClickHouse to skip entire granules when scanning data using the primary key.

 

To understand this concept better, let’s create a table and experiment with it.

 

Step 1: Create a database demo_db.

CREATE DATABASE IF NOT EXISTS demo_db;

   

Step 2: Create a Table with index_granularity = 4.

 

CREATE TABLE demo_db.orders_granule_example
(
    order_id UInt32,
    user_id UInt32,
    order_date Date,
    amount Float64
)
ENGINE = MergeTree
ORDER BY (user_id)
SETTINGS index_granularity = 4;

   

Step 3: Insert 12 records into the orders_granule_example table.

 

INSERT INTO demo_db.orders_granule_example VALUES
(1, 101, '2025-05-10', 200.0),
(2, 102, '2025-05-11', 300.0),
(3, 103, '2025-05-12', 400.0),
(4, 104, '2025-05-13', 500.0),
(5, 105, '2025-05-14', 600.0),
(6, 106, '2025-05-15', 700.0),
(7, 107, '2025-05-16', 800.0),
(8, 108, '2025-05-17', 900.0),
(9, 109, '2025-05-18', 1000.0),
(10, 110, '2025-05-19', 1100.0),
(11, 111, '2025-05-20', 1200.0),
(12, 112, '2025-05-21', 1300.0);

krishna :) SELECT * FROM demo_db.orders_granule_example;

SELECT *
FROM demo_db.orders_granule_example

Query id: 28bdc975-5b01-4963-a057-382595950c31

    ┌─order_id─┬─user_id─┬─order_date─┬─amount─┐
 1. │        1 │     101 │ 2025-05-10 │    200 │
 2. │        2 │     102 │ 2025-05-11 │    300 │
 3. │        3 │     103 │ 2025-05-12 │    400 │
 4. │        4 │     104 │ 2025-05-13 │    500 │
 5. │        5 │     105 │ 2025-05-14 │    600 │
 6. │        6 │     106 │ 2025-05-15 │    700 │
 7. │        7 │     107 │ 2025-05-16 │    800 │
 8. │        8 │     108 │ 2025-05-17 │    900 │
 9. │        9 │     109 │ 2025-05-18 │   1000 │
10. │       10 │     110 │ 2025-05-19 │   1100 │
11. │       11 │     111 │ 2025-05-20 │   1200 │
12. │       12 │     112 │ 2025-05-21 │   1300 │
    └──────────┴─────────┴────────────┴────────┘

12 rows in set. Elapsed: 0.005 sec. 

   

What Happens When You Insert Data?

Here we inserted 12 rows into a MergeTree table with index_granularity is equal to 4. For every 4 rows, ClickHouse creates a granule, and writes an entry to the primary index (primary.idx) for the first row in that granule.

 

Granule #  

Indexed user_id (1st Row)  

Rows Included

1

101

Rows 1–4 (user_id 101–104)

2

105

Rows 5–8 (user_id 105–108)

3

109

Rows 9–12 (user_id 109–112)

 

Contents of primary.idx

primary.idx will contain:

Entry 1 → user_id = 101  (1st row of Granule 1)

Entry 2 → user_id = 105  (1st row of Granule 2)

Entry 3 → user_id = 109  (1st row of Granule 3)

 

These are used by ClickHouse to seek to the correct granule during query execution.

 

For a query like: 

SELECT * FROM orders_granule_example WHERE user_id = 106;

   

ClickHouse looks at primary.idx and finds:

·      101 → Granule 1

·      105 → Granule 2

·      109 → Granule 3

 

It skips Granule 1 (106 > 104), reads Granule 2, since 106 is in range 105–108, skips Granule 3, since 106 < 109. In this approach, only one granule is read from disk instead of scanning all rows!

 

 

 

Previous                                                    Next                                                    Home

Sunday, 6 September 2026

Understanding Primary Key and Order By in ClickHouse MergeTree Tables

  

In ClickHouse, tables that use the MergeTree engine (or any of its family variants) require either a primary key or order keys (i.e., an ORDER BY clause). These keys play an important role in organizing data on disk and optimizing query performance.

 

Unlike traditional relational databases where a primary key enforces uniqueness, in ClickHouse, the primary key is used mainly for data sorting and indexing not for uniqueness. The ORDER BY clause defines how the data is physically stored.

 

This post explains both concepts with examples and clarifies how they work in the MergeTree family of table engines.

 

1. ORDER BY in MergeTree Tables

In ClickHouse, the ORDER BY clause determines how data is sorted inside each data part on disk. It creates a clustered index on the specified column(s). This helps ClickHouse to efficiently locate relevant rows during queries. You must specify ORDER BY when creating a MergeTree table.

CREATE DATABASE IF NOT EXISTS demo_db;

CREATE TABLE demo_db.simple_orders
(
    order_id UInt32,
    user_id UInt32,
    order_date Date,
    total_amount Float64
) 
ENGINE = MergeTree()
ORDER BY order_date;

   

Here, order_date determines the order of data stored on disk.

 

2. PRIMARY KEY in MergeTree Tables

In ClickHouse, a primary key is not used to enforce uniqueness like in traditional RDBMS systems. Instead, it's used for building an index to speed up data reads by allowing the engine to skip unnecessary rows during query execution.

 

The primary key helps ClickHouse identify data ranges efficiently when executing queries with filters, particularly on large datasets.

 

ClickHouse supports two syntaxes for defining the primary key.

 

2.1 Defining PRIMARY KEY Inside the Column List

 

CREATE TABLE demo_db.orders_by_user
(
    order_id UInt32,
    user_id UInt32,
    order_date Date,
    amount Float64,
    PRIMARY KEY(user_id)
)
ENGINE = MergeTree
ORDER BY (user_id, order_date);

   

In this example, the PRIMARY KEY(user_id) is specified inside the column definition. ClickHouse will create a sparse index on user_id.

 

2.2 Defining PRIMARY KEY Outside the Column List

 

CREATE TABLE demo_db.orders_by_user_ex
(
    order_id UInt32,
    user_id UInt32,
    order_date Date,
    amount Float64
)
ENGINE = MergeTree
ORDER BY (user_id, order_date)
PRIMARY KEY(user_id);

   

This is a functionally equivalent form, but the PRIMARY KEY clause is declared after the column definitions and engine configuration. Both styles are valid, you can use whichever suits your code style or team conventions.

 

In ClickHouse, primary keys are used for indexing, not enforcing uniqueness. That means you can insert duplicate values for the primary key columns without any error.

 

INSERT INTO demo_db.orders_by_user VALUES 
(1, 101, '2025-05-10', 150.00),
(2, 101, '2025-05-10', 200.50),
(3, 101, '2025-05-11', 180.75);

krishna :) INSERT INTO demo_db.orders_by_user VALUES 
(1, 101, '2025-05-10', 150.00),
(2, 101, '2025-05-10', 200.50),
(3, 101, '2025-05-11', 180.75);

INSERT INTO demo_db.orders_by_user FORMAT Values

Query id: 6db2f88f-7384-4c75-966c-ad2c6fb1ca7f

Ok.

3 rows in set. Elapsed: 0.025 sec. 

krishna :) ;

Empty query

krishna :) SELECT * FROM demo_db.orders_by_user;

SELECT *
FROM demo_db.orders_by_user

Query id: 34df6974-6019-4774-a1d7-97fe25219440

   ┌─order_id─┬─user_id─┬─order_date─┬─amount─┐
1. │        1 │     101 │ 2025-05-10 │    150 │
2. │        2 │     101 │ 2025-05-10 │  200.5 │
3. │        3 │     101 │ 2025-05-11 │ 180.75 │
   └──────────┴─────────┴────────────┴────────┘

3 rows in set. Elapsed: 0.005 sec. 

  

 

Previous                                                    Next                                                    Home