# ClickHouse: A Practical Guide to Fast Analytics

The dashboard was quick when the events table had a million rows. At two hundred million, the "visits per day by country" chart takes forty seconds and someone has added a loading spinner. You have added indexes. You have added a read replica. It is still slow.

The trouble is not your tuning. A database built for looking up single orders stores each row together, so to add up one column it must read all the others too. Analytics needs the opposite layout, and that is what ClickHouse provides.

## What ClickHouse is

ClickHouse is an open-source, column-oriented database for analytics, often called OLAP (online analytical processing). It was created at Yandex for web analytics, is now developed by ClickHouse, Inc. and a large community, and is released under the Apache 2.0 licence. You can run it yourself or use a managed service such as ClickHouse Cloud.

You query it with SQL. What differs is how it stores and processes data:

- **Columns are stored separately.** A query that needs three columns out of fifty reads only those three.
- **Columns compress very well.** Similar values sit next to each other, so data takes far less disk, and less disk means less to read.
- **Queries are processed in batches of values** across all CPU cores, not row by row.

The result is that aggregations over hundreds of millions or billions of rows often finish in well under a second on modest hardware.

## Row store or column store?

| | Row store (PostgreSQL, MySQL) | Column store (ClickHouse) |
|---|---|---|
| Built for | Many small reads and writes | Few large reads over many rows |
| Typical query | "Fetch order 42" | "Revenue per day for the last year" |
| Inserts | One row at a time is fine | Batches of thousands of rows |
| Updates and deletes | Cheap and immediate | Possible, but heavy and asynchronous |
| Transactions | Full ACID across tables | Limited |
| Primary key | Unique, finds one row | Not unique, finds ranges of rows |

They are complements. The common setup is a row store for the application and ClickHouse beside it for analytics.

## Where ClickHouse fits, and where it does not

**A strong choice for:**

- Product and web analytics
- Logs, metrics and traces
- Dashboards that customers or staff query live
- Time-series data at volume
- Any large, append-mostly table that you mainly aggregate

**Look elsewhere when:**

- **It would be your application's main database.** Frequent single-row updates, unique constraints and multi-table transactions belong in PostgreSQL or MySQL.
- **Your data is small.** A few million rows aggregate fine in the database you already have. For local analysis of files, DuckDB is lighter still.
- **You mostly fetch single rows by key.** A row store or a key-value store does that better.
- **You want zero operations and elastic pricing above all.** A cloud warehouse such as BigQuery or Snowflake trades some speed and cost control for less to manage.

## Using it the right way

Start a server with Docker and open the client:

```bash
docker run -d --name clickhouse -p 8123:8123 -p 9000:9000 clickhouse/clickhouse-server
docker exec -it clickhouse clickhouse-client
```

Port 8123 is the HTTP interface and 9000 is the native protocol.

### The table design is the tuning

```sql
CREATE TABLE page_views (
  event_time  DateTime,
  user_id     UInt64,
  country     LowCardinality(String),
  url         String,
  duration_ms UInt32
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(event_time)
ORDER BY (country, event_time);
```

Three decisions here shape everything that follows.

**The engine.** `MergeTree` is the standard engine family. Each insert writes a new immutable "part" on disk, and ClickHouse merges parts in the background.

**`ORDER BY`, the sorting key.** Data on disk is sorted by these columns, and ClickHouse keeps a small sparse index of the sorted values. A query that filters on the leading columns can skip most of the table. Choose the columns you filter by most, with the lower-cardinality ones (fewer distinct values) first. This is not a unique key: two rows may share the same values.

**`PARTITION BY`.** Partitions are for managing data, such as dropping a whole month in an instant, more than for speed. Keep them coarse. Monthly is a safe default. Partitioning by a column with thousands of values creates a flood of tiny parts and is one of the commonest ways to hurt a ClickHouse server.

### Use precise types

- Pick the smallest number type that fits: `UInt8`, `UInt32`, `DateTime` instead of `Int64` and strings for everything.
- Wrap repetitive strings (country, status, browser) in `LowCardinality(...)`, which stores them through a dictionary.
- Avoid `Nullable` unless you truly need to tell "missing" from a default value. It adds a hidden column and slows things down.

### Insert in batches

Every insert creates a part. A thousand single-row inserts a second create parts faster than merges can combine them, and the server eventually answers with a "too many parts" error.

Send rows in large batches, thousands at a time, at most about once a second. If your application cannot batch, let the server do it:

```sql
INSERT INTO page_views
SETTINGS async_insert = 1, wait_for_async_insert = 1
VALUES (now(), 42, 'IN', '/pricing', 1840);
```

With asynchronous inserts, ClickHouse buffers small inserts and writes them together.

### Query only what you need

```sql
SELECT
  toStartOfDay(event_time) AS day,
  count() AS views,
  uniq(user_id) AS visitors,
  quantile(0.95)(duration_ms) AS p95_duration_ms
FROM page_views
WHERE country = 'IN'
  AND event_time >= now() - INTERVAL 30 DAY
GROUP BY day
ORDER BY day;
```

Because storage is by column, naming four columns reads four columns. `SELECT *` reads all of them and throws away the advantage. `uniq()` is an approximate distinct count that is much faster than an exact one; use `uniqExact()` when you need precision.

To see whether the sorting key is helping:

```sql
EXPLAIN indexes = 1
SELECT count() FROM page_views
WHERE country = 'IN' AND event_time >= now() - INTERVAL 1 DAY;
```

The output shows how many parts and granules (blocks of rows) were selected out of the total.

### Pre-aggregate with a materialized view

In ClickHouse a materialized view is a trigger on insert: each new batch is transformed and written into another table. That lets you keep a small, always-current summary.

```sql
CREATE TABLE views_per_day (
  day     Date,
  country LowCardinality(String),
  views   UInt64
)
ENGINE = SummingMergeTree
ORDER BY (day, country);

CREATE MATERIALIZED VIEW views_per_day_mv TO views_per_day AS
SELECT toDate(event_time) AS day, country, count() AS views
FROM page_views
GROUP BY day, country;
```

`SummingMergeTree` adds up rows with the same key when parts merge. Merges happen in the background at no fixed time, so always aggregate when you read:

```sql
SELECT day, sum(views) AS views
FROM views_per_day
WHERE country = 'IN'
GROUP BY day
ORDER BY day;
```

The view only sees rows inserted after it was created. Fill in older data with an `INSERT ... SELECT`.

### Expire old data automatically

```sql
ALTER TABLE page_views MODIFY TTL event_time + INTERVAL 90 DAY;
```

Rows older than 90 days are removed during merges, with no delete jobs to schedule.

### Treat updates and deletes as exceptions

`ALTER TABLE ... UPDATE` and `ALTER TABLE ... DELETE` are "mutations": they rewrite whole data parts in the background. They are fine for occasional corrections or privacy requests, and wrong for routine application logic. If your data changes, model it as new rows, for example with `ReplacingMergeTree`, which keeps the latest version of each key when parts merge.

## Common mistakes

- **Row-at-a-time inserts.** The cause of most "too many parts" errors. Batch, or use asynchronous inserts.
- **A random or high-cardinality first column in `ORDER BY`.** Sorting by a UUID first makes the index useless for range filters and hurts compression.
- **Over-partitioning.** Partitioning by day and customer creates huge numbers of parts. Stay with months unless you have a clear reason.
- **Expecting uniqueness.** The primary key does not prevent duplicates. If a batch is retried with different contents, you get both.
- **Reading a merging table without aggregating.** `SummingMergeTree` and `ReplacingMergeTree` tidy up eventually, not instantly. Use `sum()` and `GROUP BY`, or `FINAL` where the cost is acceptable.
- **`SELECT *` on wide tables.** It reads every column.
- **Joining two huge tables carelessly.** By default the right-hand table of a join is loaded into memory. Put the smaller table on the right, or denormalise the data at insert time.
- **Running `OPTIMIZE TABLE ... FINAL` on a schedule.** It forces a full rewrite. Let background merges do their job.
- **An open server.** Set a password for the `default` user and do not expose the ports without TLS.

## Quick reference

| Task | Command |
|---|---|
| Open the client | `clickhouse-client --host host --user default --password` |
| List tables | `SHOW TABLES;` |
| Table definition | `SHOW CREATE TABLE page_views;` |
| Running queries | `SELECT query_id, elapsed, query FROM system.processes;` |
| Stop a query | `KILL QUERY WHERE query_id = '...';` |
| Table sizes | `SELECT table, formatReadableSize(sum(bytes_on_disk)) AS size, sum(rows) AS rows FROM system.parts WHERE active GROUP BY table;` |
| Parts per partition | `SELECT partition, count() FROM system.parts WHERE active AND table = 'page_views' GROUP BY partition;` |
| Running mutations | `SELECT * FROM system.mutations WHERE NOT is_done;` |
| Version | `SELECT version();` |

ClickHouse asks you to decide a few things up front: the sorting key, coarse partitions and batched inserts. Get those right and the forty-second dashboard becomes one that feels instant.

## Exploring ClickHouse with CreamDB

`clickhouse-client` is quick, but analytics is easier to judge when you can see a chart. [CreamDB](https://www.creamdb.com) connects to ClickHouse over its HTTP interface from a browser tab, with nothing to install.

- Browse databases and tables in a tree. Open a table in a grid where paging, sorting and filtering are done by ClickHouse, so a huge table is never pulled into your browser.
- Write SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- Watch running queries and server metrics in the Status panel, and read users and roles on a read-only page.
- Ask in plain English, for example "visitors per day by country for the last month", and get the SQL, a result table and a chart.

The assistant only reads on its own. Any change waits as an approval card that you answer, and read-only mode on the server blocks writes.

CreamDB is a hosted service, so the ClickHouse server has to be reachable from the internet. Use its HTTPS port so the password and data are encrypted on the way; ClickHouse Cloud offers that by default.

It is free to start.

