---
name: clickhouse-hello-world
description: |-
  Create your first ClickHouse table, insert data, and run analytical queries.
  Use when starting a new ClickHouse project, learning MergeTree basics,
  or testing your ClickHouse connection with real operations.
  Trigger with "clickhouse hello world", "first clickhouse table",
  "clickhouse quick start", "create clickhouse table", "clickhouse example".
allowed-tools: Read, Write, Edit, Bash(npm:*), Bash(node:*)
version: 1.7.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
tags:
  - saas
  - database
  - analytics
  - clickhouse
  - olap
compatibility: Designed for Claude Code
title: clickhouse-hello-world
canonical_url: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world
last_updated: 2026-10-07T06:06:28.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/mergetree-and-types.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/mergetree-and-types.md), [references/system-tables.md](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/system-tables.md).
>
> If the user asked to install this Skill, run `npx skilld install jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/clickhouse-hello-world`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/clickhouse-hello-world`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/clickhouse-hello-world --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/clickhouse-hello-world --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# ClickHouse Hello World

## Overview

Create a MergeTree table, insert rows with JSONEachRow, and run your first
analytical query -- all using the official `@clickhouse/client`. This is the
smoke test that proves your connection works and teaches the four MergeTree
concepts (`ORDER BY`, `PARTITION BY`, `TTL`, `LowCardinality`) reused in every
real schema.

## Prerequisites

- `@clickhouse/client` installed and connected (see the `clickhouse-install-auth`
  skill for connection setup).
- A reachable ClickHouse server (local Docker, ClickHouse Cloud, or self-hosted)
  with `CLICKHOUSE_HOST` / `CLICKHOUSE_USER` / `CLICKHOUSE_PASSWORD` set as
  environment variables.

## Instructions

### Step 1: Create a MergeTree Table

```typescript
import { createClient } from '@clickhouse/client';

const client = createClient({
  url: process.env.CLICKHOUSE_HOST ?? 'http://localhost:8123',
  username: process.env.CLICKHOUSE_USER ?? 'default',
  password: process.env.CLICKHOUSE_PASSWORD ?? '',
});

await client.command({
  query: `
    CREATE TABLE IF NOT EXISTS events (
      event_id    UUID DEFAULT generateUUIDv4(),
      event_type  LowCardinality(String),
      user_id     UInt64,
      payload     String,
      created_at  DateTime DEFAULT now()
    )
    ENGINE = MergeTree()
    ORDER BY (event_type, created_at)
    PARTITION BY toYYYYMM(created_at)
    TTL created_at + INTERVAL 90 DAY
  `,
});
console.log('Table "events" created.');
```

**Key concepts:**

- `MergeTree()` -- the foundational ClickHouse engine for analytics
- `ORDER BY` -- defines the primary index (sort key); pick columns you filter/group on
- `PARTITION BY` -- splits data into parts by month for efficient pruning
- `TTL` -- automatic data expiration
- `LowCardinality(String)` -- dictionary-encoded string, ideal for columns with < 10K distinct values

For the full engine menu (`ReplacingMergeTree`, `SummingMergeTree`, etc.) and the
column-type table, see [MergeTree engines & data types](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/mergetree-and-types.md).

### Step 2: Insert Data with JSONEachRow

```typescript
await client.insert({
  table: 'events',
  values: [
    { event_type: 'page_view', user_id: 1001, payload: '{"url":"/home"}' },
    { event_type: 'click',     user_id: 1001, payload: '{"button":"signup"}' },
    { event_type: 'page_view', user_id: 1002, payload: '{"url":"/pricing"}' },
    { event_type: 'purchase',  user_id: 1002, payload: '{"amount":49.99}' },
    { event_type: 'page_view', user_id: 1003, payload: '{"url":"/docs"}' },
  ],
  format: 'JSONEachRow',
});
console.log('Inserted 5 events.');
```

### Step 3: Query the Data

```typescript
// Count events by type
const rs = await client.query({
  query: `
    SELECT
      event_type,
      count()          AS total,
      uniqExact(user_id) AS unique_users
    FROM events
    GROUP BY event_type
    ORDER BY total DESC
  `,
  format: 'JSONEachRow',
});

const rows = await rs.json<{
  event_type: string;
  total: string;        // ClickHouse returns numbers as strings in JSON
  unique_users: string;
}>();

for (const row of rows) {
  console.log(`${row.event_type}: ${row.total} events, ${row.unique_users} users`);
}
```

### Step 4: Explore System Tables (optional)

Once data lands, inspect on-disk size and part counts via `system.parts` to
confirm your partitioning is healthy. Full query and column reference:
[exploring system tables](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/system-tables.md).

## Output

Running the three core steps against a fresh table produces:

- **Step 1** -- `Table "events" created.` (idempotent via `IF NOT EXISTS`).
- **Step 2** -- `Inserted 5 events.`
- **Step 3** -- one aggregated row per `event_type`, sorted by count descending:

```
page_view: 3 events, 3 users
click: 1 events, 1 users
purchase: 1 events, 1 users
```

ClickHouse returns numeric aggregates as JSON strings, so cast `total` /
`unique_users` before doing arithmetic in TypeScript.

## Error Handling

| Error | Cause | Solution |
|-------|-------|----------|
| `Table already exists` | Re-running CREATE | Use `IF NOT EXISTS` |
| `Unknown column` | Typo in column name | Check `DESCRIBE TABLE events` |
| `Type mismatch` | Wrong data type in insert | Match types to schema |
| `Memory limit exceeded` | Query too broad | Add WHERE clauses, use LIMIT |

## Examples

Steps 1-3 form the canonical end-to-end example: create → insert → aggregate.
Two extensions live in the reference files:

- **Different engine or column types** -- swap `MergeTree` for
  `ReplacingMergeTree` (upserts) or add a `Decimal(18,2)` column:
  [MergeTree engines & data types](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/mergetree-and-types.md).
- **Verifying on-disk layout** -- the `system.parts` size/part-count query:
  [exploring system tables](https://skilld.dev/api/skills-raw/jeremylongshore/tons-of-skills-marketplace/clickhouse-hello-world/references/system-tables.md).

## Resources

- [MergeTree Engine Docs](https://clickhouse.com/docs/engines/table-engines/mergetree-family/mergetree)
- [Data Types Reference](https://clickhouse.com/docs/sql-reference/data-types)
- [CREATE TABLE Syntax](https://clickhouse.com/docs/sql-reference/statements/create/table)

## Next Steps

Proceed to the `clickhouse-local-dev-loop` skill for Docker-based local
development and an iterative schema-editing workflow.
