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
- Python 3.9 or newer on Linux or macOS with pip
- pandas (only for the last step)
- Roughly 500 MB of free disk space for the chdb package and test data
Steps
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.
bashpip install chdb==4.5.1 python3 -c "import chdb; print('chdb', chdb.__version__); print(chdb.query('SELECT version()', 'TSV'))"Expected outputchdb 4.5.1 26.11.1.1Open 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.
pythonfrom 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 │ └────────────┘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.
pythonsess.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 output5Run 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.
pythonprint(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 │ └─────────┴───────┴───────┴────────┘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.
pythonsess.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 outputPrimaryKey Granules: 26/123 Skip Name: idx_user Granules: 3/26 4Check 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.
pythonprint(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 │ └─────────┴────────────┴──────────────┘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.
pythonsess.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 │ └─────────┴───────┘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.
pythondf = 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 outputhour 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
- Install a ClickHouse server or try ClickHouse Cloud and run the same SQL over the network
- Learn materialized views for pre-aggregating data as it arrives
- Choose ORDER BY keys based on your most common filters, since they matter more than secondary indexes
- See ClickBench results on DatabaseRadar to compare ClickHouse with other analytical engines
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
- Getting started with DuckDB in Python
- Getting started with LanceDB in Python
- Getting started with PostgreSQL
- Getting started with Redis
- Getting started with SQLite in Python
Sources
Last verified:
- clickhouse.com/docs clickhouse.com
- clickhouse.com/docs/chdb clickhouse.com
- clickhouse.com/docs/engines/table-engines/mergetree-family/mergetree clickhouse.com
- clickhouse.com/docs/optimize/skipping-indexes clickhouse.com
- clickhouse.com/docs/sql-reference/table-functions/file clickhouse.com
- github.com/chdb-io/chdb github.com
Found an error? See how to report a correction.