DEV Community

Cover image for SQL Server to ClickHouse with CDC: A Step-by-Step Docker Tutorial
Shubham Baldava
Shubham Baldava

Posted on

SQL Server to ClickHouse with CDC: A Step-by-Step Docker Tutorial

SQL Server to ClickHouse usually comes up when reports start slowing down the database that takes the orders. ClickHouse is built for those scans and group-bys, but the rows are still written in SQL Server and keep changing after the first copy. Every insert, update and delete has to follow them across.

SQL Server already records those changes if you let it. Turn on change data capture (CDC) and a SQL Server Agent job copies each change from the transaction log into a change table. Pipelines differ in what reads those tables, and where the rows land.

The usual ways to move SQL Server data into ClickHouse

  • Debezium, Kafka and the ClickHouse Kafka engine. Seconds of latency, but you run Kafka, Kafka Connect, the Debezium SQL Server connector and a materialized view per table, and updates and deletes need your own merge logic.
  • The ClickHouse ODBC table function. Nothing is copied: every query goes to SQL Server through an Open Database Connectivity (ODBC) driver and a data source name (DSN) on each ClickHouse server.
  • Export and load. The bcp utility or SQL Server Integration Services (SSIS) writes files, and INSERT ... SELECT FROM s3(...) loads them. Hours to daily, full reloads only.
  • Managed extract, load and transform (ELT). Fivetran, Estuary or Airbyte Cloud. Nothing to host, minutes by plan, and a second copy in ClickHouse priced per row, per GB or per connector.

This tutorial takes a fifth route. OLake Go is an open source (Apache 2.0) replication tool that reads the change tables and commits the rows as Apache Iceberg tables into an Apache Polaris catalog. ClickHouse attaches that catalog as a database, and DuckDB and Trino read the same tables from the same endpoint.

I ran every step below on 2026-10-30, all in Docker: SQL Server 2022 Developer, OLake Go v1.1.0 through OLake UI, Polaris 1.8.0 on MinIO, and ClickHouse 26.8.36 LTS (long-term support). The timings and row counts in this post come from that run.

What the SQL Server to ClickHouse pipeline looks like

  • Source: a database shop with two CDC-enabled tables, dbo.customers and dbo.orders.
  • Pipeline: OLake UI on localhost:8000. The first sync records the current log sequence number (LSN) and copies each table in parallel chunks; later syncs read the change tables from that LSN.
  • Catalog: Polaris, an open source Iceberg REST (Representational State Transfer) catalog, over a MinIO bucket called lakehouse.
  • Readers: ClickHouse through its DataLakeCatalog engine, plus DuckDB and Trino.

You need: Docker, a SQL Server edition with CDC (Developer, Standard 2016 SP1 or later, or Enterprise), ClickHouse 26.1 or later, and about 40 minutes.

Step 1: Turn on CDC in SQL Server

If you want a throwaway server, start one with the Agent switched on. The capture job is an Agent job, and a container leaves the Agent off by default:

docker run -d --name mssql \
  -e ACCEPT_EULA=Y \
  -e MSSQL_SA_PASSWORD='<a strong password>' \
  -e MSSQL_AGENT_ENABLED=true \
  -p 1433:1433 \
  mcr.microsoft.com/mssql/server:2022-latest
Enter fullscreen mode Exit fullscreen mode

Create a database shop and the two tables. My run started with 8 customers and 40 orders; insert whatever you like:

CREATE TABLE dbo.customers (
  id INT IDENTITY(1,1) PRIMARY KEY,
  name NVARCHAR(100), email NVARCHAR(200), city NVARCHAR(100), tier NVARCHAR(20),
  created_at DATETIME2 DEFAULT SYSUTCDATETIME(),
  updated_at DATETIME2 DEFAULT SYSUTCDATETIME());

CREATE TABLE dbo.orders (
  id INT IDENTITY(1,1) PRIMARY KEY,
  customer_id INT REFERENCES dbo.customers(id),
  product NVARCHAR(100), amount DECIMAL(10,2), status NVARCHAR(20),
  created_at DATETIME2 DEFAULT SYSUTCDATETIME(),
  updated_at DATETIME2 DEFAULT SYSUTCDATETIME());
Enter fullscreen mode Exit fullscreen mode

Then enable CDC on the database and each table, and create a read-only login. The last block matters more than it looks:

USE shop;
EXEC sys.sp_cdc_enable_db;
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'customers', @role_name = NULL;
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'orders',    @role_name = NULL;

USE master;
CREATE LOGIN olake WITH PASSWORD = '<password>';
USE shop;
CREATE USER olake FOR LOGIN olake;
GRANT SELECT ON SCHEMA :: dbo TO olake;
GRANT SELECT ON SCHEMA :: cdc TO olake;
GRANT VIEW DATABASE STATE TO olake;

-- OLake Go reads the capture job definition from msdb
USE msdb;
CREATE USER olake FOR LOGIN olake;
GRANT SELECT ON dbo.cdc_jobs TO olake;
Enter fullscreen mode Exit fullscreen mode

Confirm it took:

SELECT name, is_cdc_enabled FROM sys.databases WHERE name = 'shop';   -- 1
SELECT capture_instance FROM cdc.change_tables;                        -- dbo_customers, dbo_orders
EXEC msdb.dbo.sp_help_job @job_name = N'cdc.shop_capture';             -- the Agent job exists
Enter fullscreen mode Exit fullscreen mode

On a production server, keep four things in mind:

  • No Agent, no changes. A stopped Agent leaves the change tables empty, with no error. EXEC master.dbo.xp_servicecontrol 'QueryState', 'SQLServerAgent' answers Running. when it is up.
  • Three days of change rows. A job paused longer needs a fresh snapshot, so raise retention with sys.sp_cdc_change_job before a planned pause.
  • Hosted servers use msdb.dbo.rds_cdc_enable_db on Amazon Relational Database Service (RDS) or msdb.dbo.gcloudsql_cdc_enable_db on Cloud SQL for the database step.
  • Primary keys. Without one, inserts replicate but updates and deletes are not applied.

Step 2: Start Polaris and MinIO, then create the catalog

Polaris stores pointers and permissions, not data. It hands short-lived storage credentials to OLake Go and to each engine, so no store keys need to sit in ClickHouse. Save this as docker-compose.yml and run docker compose up -d:

services:
  minio:
    image: minio/minio
    hostname: lake-minio
    command: server /data --console-address ":9001"
    environment: { MINIO_ROOT_USER: minioadmin, MINIO_ROOT_PASSWORD: minioadmin }
    ports: ["9000:9000", "9001:9001"]
  polaris:
    image: apache/polaris:latest
    depends_on: [minio]
    ports: ["8181:8181", "8182:8182"]
    environment:
      AWS_REGION: us-east-1
      AWS_ACCESS_KEY_ID: minioadmin
      AWS_SECRET_ACCESS_KEY: minioadmin
      POLARIS_BOOTSTRAP_CREDENTIALS: POLARIS,root,<root-secret>
      polaris.realm-context.realms: POLARIS
Enter fullscreen mode Exit fullscreen mode

Now create the bucket, a catalog called olake, a principal for OLake Go and the engines, and the grant that lets it write:

P=http://localhost:8181
aws --endpoint-url http://localhost:9000 s3 mb s3://lakehouse

TOKEN=$(curl -s $P/api/catalog/v1/oauth/tokens -H 'Polaris-Realm: POLARIS' \
  -d grant_type=client_credentials -d client_id=root -d client_secret=<root-secret> \
  -d scope=PRINCIPAL_ROLE:ALL | jq -r .access_token)
H=(-H "Authorization: Bearer $TOKEN" -H 'Polaris-Realm: POLARIS' -H 'Content-Type: application/json')

curl -s "${H[@]}" $P/api/management/v1/catalogs -d '{"catalog": {
  "name": "olake", "type": "INTERNAL", "readOnly": false,
  "properties": {"default-base-location": "s3://lakehouse/olake"},
  "storageConfigInfo": {"storageType": "S3", "allowedLocations": ["s3://lakehouse/olake"],
    "endpoint": "http://<minio-host>:9000/", "endpointInternal": "http://lake-minio:9000",
    "pathStyleAccess": true, "region": "us-east-1"}}}'

curl -s "${H[@]}" $P/api/management/v1/principals -d '{"principal": {"name": "olake"}}'

curl -s "${H[@]}" $P/api/management/v1/principal-roles -d '{"principalRole": {"name": "olake_role"}}'
curl -s "${H[@]}" $P/api/management/v1/catalogs/olake/catalog-roles -d '{"catalogRole": {"name": "olake_catalog_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/principals/olake/principal-roles -d '{"principalRole": {"name": "olake_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/principal-roles/olake_role/catalog-roles/olake -d '{"catalogRole": {"name": "olake_catalog_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/catalogs/olake/catalog-roles/olake_catalog_role/grants -d '{"type": "catalog", "privilege": "CATALOG_MANAGE_CONTENT"}'
Enter fullscreen mode Exit fullscreen mode

Three details in that block decide whether ClickHouse can read anything later:

  • The slash at the end of endpoint. ClickHouse 26.8 and 26.10 build the object path from this value. Without the trailing slash, every read returns a 404.
  • No underscores in hostnames. Polaris is a Java service, and Java's URI parser rejects a host such as lab_minio. That is why the container is lake-minio.
  • The principal's secret appears once, in the response to the principals call. Copy the clientId and clientSecret now.

Step 3: Start OLake UI and add the SQL Server source

curl -sSL https://raw.githubusercontent.com/datazip-inc/olake-ui/master/docker-compose-v1.yml | docker compose -f - up -d
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000 and sign in with admin / password. Under Sources, click Create Source and pick MSSQL.

Leave Enable CDC on, and leave Manage Capture Instance off unless you want to grant db_owner. SQL Server ran in another container, so the host is host.docker.internal on port 1433, with database shop, user olake and SSL off.

OLake UI Edit source form for MSSQL on OLake Go v1.1.0 with Enable CDC on, host host.docker.internal, port 1433, database shop, user olake and SSL disabled

Set up source tests the connection and then the CDC prerequisites before saving: CDC on the database, a capture instance per table, and a capture job it can read. A failed check names the setting and what to run.

Step 4: Add the Polaris destination

Under Destinations, click Create Destination, pick Apache Iceberg and set the catalog type to Polaris with OAuth2 authentication. The values from my run:

Field Value
REST Catalog URI http://host.docker.internal:8181/api/catalog
Polaris Catalog Name olake
REST Auth URI http://host.docker.internal:8181/api/catalog/v1/oauth/tokens
REST Credential <client_id>:<client_secret>
REST scope PRINCIPAL_ROLE:ALL
S3 Endpoint http://host.docker.internal:9000
AWS Region us-east-1

Add the MinIO access and secret keys, then click Create. OLake Go exchanges the credential for a token, creates a namespace and a test table, writes to the bucket and drops the test table again.

OLake UI Edit destination form for Apache Iceberg with catalog type Polaris, OAuth2 authentication, the REST catalog URI on port 8181, catalog name olake and the MinIO S3 endpoint on port 9000

Step 5: Create the job and run the first sync

Under Jobs, click Create Job, name it sql_server_to_clickhouse and pick the source and destination. The schedule sets how often the change tables are drained, not how often a full copy runs.

Under Advanced Settings, set Target Query Engines to ClickHouse, DuckDB and Trino. That is the only format decision you make: OLake Go works out a delete format all three read, and with ClickHouse in the list it chose equality deletes.

On the Streams page, tick customers and orders with Full Refresh + CDC and Upsert. Leave systranschemas unticked; enabling CDC added it, it has no capture instance, and selecting it fails the first sync.

OLake UI Streams Selection page with customers and orders selected in the dbo schema, systranschemas unticked, sync mode Full Refresh + CDC, Upsert, and Equality Deletes on Iceberg format version V2

Click Create Job, then Sync Now from the job's menu. My first sync copied 48 records (3.05 KB) in 17 seconds, container start included.

OLake UI job history for sql_server_to_clickhouse with two completed syncs, the first taking 17 seconds and the second 9 seconds

The namespace is built from the job, the source database and the schema: sql_server_to_clickhouse_shop_dbo. To pick another name, change the Iceberg DB field at the top of the Streams page before the first sync.

Step 6: Query the tables in ClickHouse

No table needs registering. In clickhouse-client, attach the whole catalog once:

SET allow_database_iceberg = 1;

CREATE DATABASE polaris
ENGINE = DataLakeCatalog('http://<polaris-host>:8181/api/catalog')
SETTINGS
  catalog_type = 'rest',
  warehouse = 'olake',
  catalog_credential = '<client_id>:<client_secret>',
  oauth_server_uri = 'http://<polaris-host>:8181/api/catalog/v1/oauth/tokens',
  auth_scope = 'PRINCIPAL_ROLE:ALL',
  vended_credentials = true,
  region = 'us-east-1';

SHOW TABLES FROM polaris;

SELECT id, name, city, tier
FROM polaris.`sql_server_to_clickhouse_shop_dbo.customers`
ORDER BY id;
Enter fullscreen mode Exit fullscreen mode

ClickHouse has one level of namespace, so the Iceberg namespace and the table name share one pair of backticks. The database is read-only.

OLake Go adds _olake_id, _op_type, _olake_timestamp and _cdc_timestamp to every table, and _cdc_start_lsn and _cdc_seqval, the log position of each change, to SQL Server tables.

Step 7: Change rows in SQL Server and sync again

This is the part a nightly export cannot do. I made 12 changes, 7 inserts and 5 updates:

INSERT INTO dbo.customers (name, email, city, tier) VALUES
  (N'Maya Patel', 'maya@example.com', N'Pune', 'silver'),
  (N'Lucas Silva', 'lucas@example.com', N'São Paulo', 'bronze');
INSERT INTO dbo.orders (customer_id, product, amount, status) VALUES
  (9, 'Laptop', 1299.00, 'placed'), (9, 'Mouse', 25.50, 'placed'),
  (10, 'Monitor', 349.99, 'placed'), (3, 'Keyboard', 89.00, 'placed'), (7, 'Webcam', 79.90, 'placed');
UPDATE dbo.customers SET tier = 'gold',       updated_at = SYSUTCDATETIME() WHERE name = N'Liam Carter';
UPDATE dbo.customers SET city = N'Abu Dhabi', updated_at = SYSUTCDATETIME() WHERE name = N'Zara Ali';
UPDATE dbo.orders    SET status = 'delivered', updated_at = SYSUTCDATETIME() WHERE id IN (1, 4, 7);
Enter fullscreen mode Exit fullscreen mode

The second sync read 12 records (855 bytes) from the change tables in 9 seconds. For customers it wrote one data file with 4 rows (2 inserts, 2 new versions) and one equality delete file covering all 4 keys. Deletes for the inserted keys are harmless, since no older row matches them.

OLake UI sync log filtered to the Iceberg commit reports for customers and orders, with addedDataFiles 1, addedEqualityDeleteFiles 1, addedRecords 4 and 8, and addedEqualityDeletes 4 and 8

Run the same SELECT again, with no refresh. Liam Carter is gold, Zara Ali is in Abu Dhabi, Maya and Lucas are new, and there is still one row per key: ClickHouse applies the equality deletes while it reads.

clickhouse-client output for polaris sql_server_to_clickhouse_shop_dbo.customers after the change sync, 10 rows with Liam Carter as gold and Zara Ali in Abu Dhabi

_op_type tells you how each row arrived: r from the snapshot, c for an insert, u for an update. The capture job runs every few seconds, so a write made just before a sync starts may only show up in the next one.

Read the same tables from DuckDB and Trino

Nothing is exported. DuckDB 1.5.5 attaches the same catalog:

INSTALL iceberg; LOAD iceberg;
INSTALL httpfs;  LOAD httpfs;

CREATE SECRET polaris_secret (
  TYPE iceberg,
  CLIENT_ID '<client_id>', CLIENT_SECRET '<client_secret>',
  OAUTH2_SERVER_URI 'http://<polaris-host>:8181/api/catalog/v1/oauth/tokens',
  OAUTH2_SCOPE 'PRINCIPAL_ROLE:ALL'
);
CREATE SECRET store_secret (
  TYPE s3, KEY_ID '<access key>', SECRET '<secret key>',
  ENDPOINT '<minio-host>:9000', URL_STYLE 'path', USE_SSL false, REGION 'us-east-1'
);
ATTACH 'olake' AS polaris (
  TYPE iceberg,
  ENDPOINT 'http://<polaris-host>:8181/api/catalog',
  SECRET polaris_secret,
  ACCESS_DELEGATION_MODE 'none'
);

SELECT id, name, city, tier FROM polaris.sql_server_to_clickhouse_shop_dbo.customers ORDER BY id;
Enter fullscreen mode Exit fullscreen mode

DuckDB 1.5.5 querying polaris.sql_server_to_clickhouse_shop_dbo.customers and returning the same 10 rows that ClickHouse returned

Trino 484 needs one catalog file with connector.name=iceberg, iceberg.catalog.type=rest and the same OAuth2 credential, and it returned the same 10 rows. An orders roll-up matched SQL Server to the cent in all three engines: 16 delivered for 8659.68, 18 placed for 10522.26 and 11 shipped for 6397.25.

Tips from the run

  • Money becomes a double. decimal, numeric and money arrive in ClickHouse as Float64. The sums matched, but round at query time when you need exact decimal arithmetic.
  • Dates land in UTC. datetime2 has no zone in SQL Server and is read as UTC, showing up as DateTime64(6, 'UTC').
  • New columns need a new capture instance. Create one by hand, or turn on Manage Capture Instance. OLake Go then adds the column on the next sync.
  • Plan compaction. Each sync adds a small data file and a delete file per table, and nothing merges them for you. Spark's rewrite_data_files works through the same Polaris endpoint.

How the SQL Server to ClickHouse options compare

Method Freshness Updates and deletes Where the data lands What you run
Debezium, Kafka, ClickHouse Kafka engine Seconds Yes, with your own merge logic Kafka topics, then ClickHouse tables Kafka, Kafka Connect, Debezium, a materialized view per table
ODBC table function Live, per query Reads the current row Nothing copied; queries hit SQL Server An ODBC driver and DSN on every ClickHouse server
bcp or SSIS export, then INSERT ... SELECT FROM s3(...) Hours to daily No, full reloads Native ClickHouse tables A script, a scheduler, a staging bucket
Fivetran, Estuary, Airbyte Cloud Minutes, by plan Varies by tool A second copy in ClickHouse Nothing; priced per row, GB or connector
OLake Go to Polaris (this post) CDC on a schedule down to one minute Yes, as Iceberg row-level deletes Iceberg tables ClickHouse, DuckDB, Trino and Spark read One Docker Compose stack, open source

With Kafka already running and a need for seconds of latency into MergeTree, Debezium is the simpler pick. A DataLakeCatalog query reads Parquet with no primary index, so load a hot slice into MergeTree on a schedule for dashboards that need it. Express and Web editions have no CDC and are limited to Full Refresh or Full Refresh + Incremental on an updated_at column.

FAQ

Can I swap MinIO for Amazon S3?

Yes. Create the catalog against an S3 bucket with an IAM (Identity and Access Management) role, and leave both endpoint and endpointInternal out of storageConfigInfo. In the OLake Go destination, leave the S3 endpoint empty.

Can ClickHouse write back into the polaris database?

No. The DataLakeCatalog database is read-only, and INSERT, ALTER and RENAME DATABASE return NOT_IMPLEMENTED. To speed up a hot query, select from it into a MergeTree table of your own.

Do deletes in SQL Server reach ClickHouse?

Yes. The capture job writes deletes to the change tables like any other change, and the next sync replays them, with _op_type set to d. That only works on tables with a primary key; without one, updates and deletes cannot be matched to a row.

Where to go from here

  • Point the source at your own SQL Server. On RDS or Cloud SQL, only the database-level CDC procedure changes.
  • To add a table, run sys.sp_cdc_enable_table for it, then tick it on the job's Streams page.
  • The full guide, with the data type table, the Trino catalog file and the troubleshooting list, is the SQL Server to ClickHouse integration page.

If a step behaves differently for you, leave a comment with the message you got and I will update the post.

Top comments (0)