Getting started with ClickHouse SQL using chDB

ClickHouse is an open-source columnar database built for fast analytical queries over very large tables. This guide uses chDB, the in-process build of the ClickHouse engine, so you can learn the SQL without running a server, and every output shown was captured from a real run.

Database profile: ClickHouse (license, deployment options, alternatives and benchmarks).

Prerequisites

Steps

  1. Install chDB, the embedded ClickHouse engine

    chDB packages the ClickHouse SQL engine as a Python library, so you can try ClickHouse SQL without running a server. The same SQL works on a full ClickHouse server or ClickHouse Cloud.

    bash
    pip install chdb==4.5.1
    python3 -c "import chdb; print('chdb', chdb.__version__); print(chdb.query('SELECT version()', 'TSV'))"
    Expected output
    chdb 4.5.1
    26.11.1.1
  2. Open a session and create a MergeTree table

    A session with a directory path keeps data on disk between runs. MergeTree is ClickHouse's main table engine, and its ORDER BY key decides how rows are sorted on disk, which also acts as the sparse primary index.

    python
    from chdb import session
    
    sess = session.Session("./chdata")
    sess.query("CREATE DATABASE IF NOT EXISTS shop")
    sess.query("""
        CREATE TABLE shop.page_views (
            ts        DateTime CODEC(Delta, ZSTD),
            user_id   UInt32,
            url       String,
            country   LowCardinality(String),
            load_ms   UInt16
        )
        ENGINE = MergeTree
        ORDER BY (country, ts)
    """)
    print(sess.query("SHOW TABLES FROM shop", "PrettyCompact"))
    Expected output
       ┌─name───────┐
    1. │ page_views │
       └────────────┘
  3. Insert rows

    ClickHouse is designed for large batched inserts rather than many single-row writes. A VALUES list is fine for a demo; real pipelines insert thousands of rows per statement or load files.

    python
    sess.query("""
        INSERT INTO shop.page_views VALUES
            ('2026-11-01 10:00:00', 1, '/home',    'DE', 120),
            ('2026-11-01 10:00:05', 2, '/pricing', 'TR', 340),
            ('2026-11-01 10:01:00', 1, '/docs',    'DE', 95),
            ('2026-11-01 10:02:30', 3, '/home',    'US', 210),
            ('2026-11-01 10:03:10', 2, '/docs',    'TR', 180)
    """)
    print(sess.query("SELECT count() FROM shop.page_views", "TSV"))
    Expected output
    5
  4. Run an aggregation

    Aggregate functions such as uniq and quantile are built in and fast. The output format is chosen per query; PrettyCompact draws a readable table.

    python
    print(sess.query("""
        SELECT country,
               count()              AS views,
               uniq(user_id)        AS users,
               round(avg(load_ms))  AS avg_ms
        FROM shop.page_views
        GROUP BY country
        ORDER BY views DESC, country
    """, "PrettyCompact"))
    Expected output
       ┌─country─┬─views─┬─users─┬─avg_ms─┐
    1. │ DE      │     2 │     1 │    108 │
    2. │ TR      │     2 │     1 │    260 │
    3. │ US      │     1 │     1 │    210 │
       └─────────┴───────┴───────┴────────┘
  5. Load a million rows and use a data-skipping index

    The numbers() table function generates synthetic rows quickly. A data-skipping index stores a small summary per block of rows, so ClickHouse can skip blocks that cannot match; EXPLAIN with indexes = 1 shows how many granules each index pruned.

    python
    sess.query("""
        INSERT INTO shop.page_views
        SELECT toDateTime('2026-11-02 00:00:00') + number,
               intDiv(number, 20),
               concat('/p/', toString(number % 2000)),
               ['DE', 'TR', 'US', 'FR', 'BR'][number % 5 + 1],
               number % 900
        FROM numbers(1000000)
    """)
    sess.query("ALTER TABLE shop.page_views ADD INDEX idx_user user_id TYPE bloom_filter GRANULARITY 1")
    sess.query("ALTER TABLE shop.page_views MATERIALIZE INDEX idx_user SETTINGS mutations_sync = 1")
    sess.query("OPTIMIZE TABLE shop.page_views FINAL")
    
    plan = sess.query("""
        EXPLAIN indexes = 1
        SELECT count() FROM shop.page_views WHERE country = 'US' AND user_id = 4242
    """, "TSV").data()
    print("\n".join(l for l in plan.splitlines() if l.strip().startswith(("PrimaryKey", "Skip", "Name", "Granules"))))
    print(sess.query("SELECT count() FROM shop.page_views WHERE country = 'US' AND user_id = 4242", "TSV"))
    Expected output
            PrimaryKey
              Granules: 26/123
            Skip
              Name: idx_user
              Granules: 3/26
    4
  6. Check columnar compression

    ClickHouse stores each column separately and compresses it, which is a large part of why scans are fast. The ts column was declared with CODEC(Delta, ZSTD), which suits steadily increasing timestamps; system.columns reports the resulting on-disk sizes.

    python
    print(sess.query("""
        SELECT name,
               formatReadableSize(data_compressed_bytes)   AS compressed,
               formatReadableSize(data_uncompressed_bytes) AS uncompressed
        FROM system.columns
        WHERE database = 'shop' AND table = 'page_views'
        ORDER BY data_uncompressed_bytes DESC
    """, "PrettyCompact"))
    Expected output
       ┌─name────┬─compressed─┬─uncompressed─┐
    1. │ url     │ 230.85 KiB │ 13.78 MiB    │
    2. │ ts      │ 4.54 KiB   │ 3.81 MiB     │
    3. │ user_id │ 979.62 KiB │ 3.81 MiB     │
    4. │ load_ms │ 21.05 KiB  │ 1.91 MiB     │
    5. │ country │ 4.81 KiB   │ 978.91 KiB   │
       └─────────┴────────────┴──────────────┘
  7. Export to Parquet and query files in place

    The file() table function reads and writes local files in many formats, so you can export results to Parquet or CSV and query those files directly without loading them into a table.

    python
    sess.query("""
        INSERT INTO FUNCTION file('top_pages.parquet', Parquet)
        SELECT url, count() AS views FROM shop.page_views GROUP BY url ORDER BY views DESC, url LIMIT 5
    """)
    print(sess.query("SELECT * FROM file('top_pages.parquet', Parquet)", "PrettyCompact"))
    Expected output
       ┌─url─────┬─views─┐
    1. │ /p/0    │   500 │
    2. │ /p/1    │   500 │
    3. │ /p/10   │   500 │
    4. │ /p/100  │   500 │
    5. │ /p/1000 │   500 │
       └─────────┴───────┘
  8. Get results as a pandas DataFrame

    Choosing the DataFrame output format returns a pandas object, which is handy for notebooks and plotting. Close the session when you are done so files are flushed cleanly.

    python
    df = sess.query("""
        SELECT toString(toStartOfHour(ts)) AS hour, count() AS views
        FROM shop.page_views
        WHERE ts >= '2026-11-02 00:00:00'
        GROUP BY hour ORDER BY hour LIMIT 3
    """, "DataFrame")
    print(df)
    print(type(df).__name__)
    sess.close()
    Expected output
                      hour  views
    0  2026-11-02 00:00:00   3600
    1  2026-11-02 01:00:00   3600
    2  2026-11-02 02:00:00   3600
    DataFrame

Next steps

FAQ

Is chDB the same as ClickHouse?
chDB embeds the ClickHouse query engine in a library, so the SQL dialect, table engines and functions are the same. It does not provide the server features such as network clients, users, replication or clustering.
Does ClickHouse have normal B-tree indexes?
No. The primary key is a sparse index built from the table's sort order, and additional data-skipping indexes such as minmax, set and bloom_filter only help ClickHouse skip blocks of rows. Picking a good ORDER BY is the main tuning lever.
Can ClickHouse handle frequent small updates?
It is optimized for appending data in batches. Updates and deletes exist but are heavier than in transactional databases, so workloads with many single-row changes usually keep a transactional database alongside ClickHouse.

More tested tutorials

All tutorials

Sources

Last verified:

  1. clickhouse.com/docs clickhouse.com
  2. clickhouse.com/docs/chdb clickhouse.com
  3. clickhouse.com/docs/engines/table-engines/mergetree-family/mergetree clickhouse.com
  4. clickhouse.com/docs/optimize/skipping-indexes clickhouse.com
  5. clickhouse.com/docs/sql-reference/table-functions/file clickhouse.com
  6. github.com/chdb-io/chdb github.com

Found an error? See how to report a correction.