Postgres to ClickHouse migration: a practical playbook

Keep Postgres for transactions and move the analytics. Type mapping, ORDER BY design, updates and deletes, batched backfill, sync, the query rewrites that bite, and how to prove parity.

To migrate from Postgres to ClickHouse, keep PostgreSQL as the system of record and move only the analytical workload: recreate the tables you report on as MergeTree-family tables with a sort key designed for your filters, backfill them in primary-key batches with the postgresql() table function, keep them current with incremental loads or change data capture, and prove parity with per-partition row counts and checksums before any dashboard switches over. ClickHouse reads only the columns a query touches and uses a sparse index to skip whole blocks of rows, which is why aggregations that crawl in Postgres come back quickly. But it does not enforce unique keys, it does not update rows in place the way Postgres does, and its columns are not nullable unless you say so. Most migration bugs come from those three differences, not from moving bytes. Every SQL example below was run against ClickHouse 26.8 and PostgreSQL 16.

Postgres vs ClickHouse for analytics: should you migrate at all?

ClickHouse complements Postgres; it does not replace it. Postgres stays the OLTP database for transactions, constraints and point reads by key. ClickHouse takes the queries that scan and aggregate many rows across a few columns.

Move when dashboard queries over large fact tables keep slowing down despite indexing, when reporting load or replica lag starts hurting the application, or when you keep building summary tables to keep dashboards responsive. Stay when your heaviest reports already finish acceptably on a replica, when reports must reflect a commit instantly, or when nobody can operate a second database. A read replica, materialized views, BRIN indexes and declarative partitioning go a long way first. No row count forces the switch; time your slowest real queries instead, and size the target with our ClickHouse sizing playbook.

Step 1: translate the schema, type by type

Ask ClickHouse what it infers before writing any DDL:

DESCRIBE TABLE postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret')
SETTINGS describe_compact_output = 1;

Treat the output as a draft: nullability follows each column’s NOT NULL constraint, and several inferred types deserve an override. ClickHouse also publishes a PostgreSQL type mapping appendix.

PostgreSQLpostgresql() infers (26.8)Recommended targetWatch out for
smallint, integer, bigint, serial, bigserialInt16, Int32, Int64SameNo sequences; keep the source id
numeric(p, s)Decimal(p, s)SamePrecision up to 76 digits
numeric (no precision)Decimal(38, 19)Decimal(P, S) sized to the dataCheck real max digits first
real, double precisionFloat32, Float64SameNever for money
booleanUInt8Bool
text, varchar(n), char(n)StringString, or LowCardinality(String)No length limit is enforced
enum typeStringLowCardinality(String) or Enum8Enum8 rejects new values until altered
uuidUUIDUUIDDo not lead the sort key with a random UUID
json, jsonbStringJSON (production-ready since 25.3) or StringJSON exposes paths as subcolumns
timestamptzDateTime64(6)DateTime64(6, 'UTC')Zone is column metadata, not per value
timestampDateTime64(6)DateTime64(6) or DateTimeDateTime is whole seconds, 1970 to 2106
dateDate32Date32, or Date for 1970 to 2149Date clamps: 9999-12-31 becomes 2149-06-06
inetStringIPv4 or IPv6
intervalStringInt64 secondsConvert in a Postgres view first
T[]Array(Nullable(T))Array(T)All rows need the same number of dimensions

NULLs: decide per column

ClickHouse columns are not nullable unless declared Nullable(T), and its documentation warns that Nullable “almost always negatively affects performance”. Each one carries a separate null mask and cannot sit in the sort key unless you enable allow_nullable_key.

Leaving it out has its own trap. With the default insert_null_as_default = 1, inserting a Postgres NULL into a non-nullable column silently stores 0, an empty string or 1970-01-01. In Postgres, avg() over 10 and NULL is 10; in ClickHouse, over 10 and a defaulted 0, it is 5. Keep Nullable where NULL means something to a metric (an unknown discount, an unshipped order) and use plain types elsewhere.

Timestamps: pin the reader to UTC

PostgreSQL stores timestamptz in UTC but, per its date/time documentation, converts it to the session TimeZone on output. postgresql() reads rows as text, and the inferred column carries no offset. In our test, a reading role set to America/New_York shifted every timestamp by five hours, silently. Use a dedicated role pinned to UTC:

-- Run in PostgreSQL
CREATE ROLE ch_reader LOGIN PASSWORD 'secret';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ch_reader;
ALTER ROLE ch_reader SET timezone = 'UTC';

Step 2: choose the engine and an ORDER BY that is not your primary key

In Postgres the primary key is a unique B-tree index. In ClickHouse, ORDER BY decides how rows are sorted on disk, and the primary index built from it is sparse: one entry per granule of 8,192 rows by default, used to skip granules that cannot match. Nothing about it is unique; insert the same id twice and you have two rows.

Choose the sort key for how you filter: lead with columns that appear in most WHERE clauses, lower cardinality first, stop at four or five columns, and end with the Postgres primary key if rows ever change. Partition by month at most, or not at all; one insert block spanning more than 100 partitions fails by default (max_partitions_per_insert_block), which is how daily-partitioned backfills die.

For a table that receives updates, use ReplacingMergeTree with a version column and a delete flag:

CREATE TABLE analytics.orders
(
    id          Int64,
    customer_id Int32,
    status      LowCardinality(String),
    amount      Decimal(12, 2),
    discount    Nullable(Decimal(18, 4)),
    note        String,
    attrs       JSON,
    created_at  DateTime64(6, 'UTC'),
    updated_at  DateTime64(6, 'UTC'),
    ship_date   Nullable(Date32),
    is_deleted  UInt8 DEFAULT 0
)
ENGINE = ReplacingMergeTree(updated_at, is_deleted)
PARTITION BY toYYYYMM(created_at)
ORDER BY (customer_id, created_at, id);

Two rules keep it correct. Every ORDER BY column must be immutable for a given row, because the sort key is what identifies duplicates. The partition key must be immutable too, because merges never compare rows across partitions. The ClickHouse ReplacingMergeTree guide covers both. Append-only tables can use plain MergeTree.

Step 3: plan for updates and deletes

Each mechanism has its own cost profile:

  • Re-insert with a higher version. The default for changing data. Old and new rows coexist until an unscheduled background merge keeps the highest updated_at; read with FINAL for current state.
  • Tombstones. A Postgres delete becomes a re-insert with is_deleted = 1 and a newer version, which FINAL hides.
  • Lightweight DELETE. Marks rows in a hidden _row_exists mask and drops them at merge time. Large delete volumes slow reads.
  • Lightweight UPDATE. Writes patch parts. Still marked beta, needs the enable_block_number_column and enable_block_offset_column table settings, and is designed for up to roughly 10% of a table.
  • Mutations. ALTER TABLE ... UPDATE rewrites whole data parts. Fine for a one-off fix, wrong for a steady stream.
-- Current state: duplicates and tombstones resolved at read time
SELECT status, count() AS orders, sum(amount) AS revenue
FROM analytics.orders FINAL
GROUP BY status;

-- Order 16 was deleted in Postgres: write a tombstone with a newer version
INSERT INTO analytics.orders
SELECT * REPLACE (now64(6) AS updated_at, 1 AS is_deleted)
FROM analytics.orders FINAL
WHERE id = 16;

FINAL adds work per query; filtering on sort-key columns limits it, and SETTINGS final = 1 applies it to every table in a query.

Step 4: backfill in primary-key batches

Per the postgresql() table function docs, each read runs as COPY (SELECT ...) TO STDOUT in a read-only transaction. Simple WHERE conditions (=, !=, >, >=, <, <=, IN) are pushed down to Postgres; joins, aggregations and sorting run in ClickHouse. So batch on an indexed column:

INSERT INTO analytics.orders
    (id, customer_id, status, amount, discount, note, attrs,
     created_at, updated_at, ship_date)
SELECT id, customer_id, status, amount, discount, note, attrs,
       created_at, updated_at, ship_date
FROM postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret')
WHERE id > 0 AND id <= 100000;

Loop over ranges from a script. Read from a replica, since a long COPY on the primary holds a transaction open and holds back vacuum. Size batches to finish in a few minutes, so a failure costs one batch. On ReplacingMergeTree a retried batch only adds duplicates that FINAL resolves; on plain MergeTree, delete the id range before retrying.

Step 5: keep it in sync

The simplest shape is a scheduled pull on a watermark, plus a nightly sweep for hard deletes:

-- Every few minutes: rows changed since the last load, with an overlap
INSERT INTO analytics.orders
    (id, customer_id, status, amount, discount, note, attrs,
     created_at, updated_at, ship_date)
SELECT id, customer_id, status, amount, discount, note, attrs,
       created_at, updated_at, ship_date
FROM postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret')
WHERE updated_at > (SELECT max(updated_at) - INTERVAL 15 MINUTE
                    FROM analytics.orders WHERE is_deleted = 0);

-- Nightly: remove rows that no longer exist in Postgres
DELETE FROM analytics.orders
WHERE id NOT IN
    (SELECT id FROM postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret'));

Every write must bump an indexed updated_at, and two details matter. Take the watermark from source rows only: in our test, a tombstone stamped with ClickHouse’s now64() was newer than pending Postgres changes, and the next pull skipped them. And re-read an overlap, because Postgres now() is the transaction start time, so a slow transaction can commit rows older than your watermark; re-read rows merge away in a ReplacingMergeTree.

The alternative is change data capture: Debezium, Airbyte, or ClickPipes and PeerDB read the Postgres write-ahead log and land each change as a versioned row, with deletes included, at the cost of a replication slot to watch. We compare them in CDC to ClickHouse: Debezium, Airbyte, ClickPipes. ClickHouse’s own MaterializedPostgreSQL database engine is still experimental and not supported in ClickHouse Cloud.

Step 6: rewrite the queries that change meaning

These constructs run fine in ClickHouse and return a different answer:

Postgres habitWhat ClickHouse doesRewrite
LEFT JOIN ... WHERE c.id IS NULL anti-joinUnmatched columns get type defaults, not NULL (join_use_nulls = 0), so nothing matchesLEFT ANTI JOIN, or SETTINGS join_use_nulls = 1
7 / 2 returns 3Returns 3.5; / is floating-pointintDiv(7, 2)
ORDER BY x DESC puts NULLs firstNULLs sort last in both directionsWrite NULLS FIRST explicitly
lag(x) is NULL on the first rowReturns 0 or '' for non-nullable columnslag(toNullable(x))
RANGE BETWEEN INTERVAL '1 hour' PRECEDINGINTERVAL frame offsets are not supportedNumeric offset in seconds
count(DISTINCT x)Exact (uniqExact), memory-hungry at high cardinalityuniq(x) where approximate is fine
ORDER BY created_at LIMIT 10 with tiesTies return in arbitrary orderAdd the id as a tie-breaker

The anti-join is the one that silently empties a report:

-- Orders whose customer is missing from the dimension table
SELECT DISTINCT o.customer_id
FROM analytics.orders AS o
LEFT ANTI JOIN analytics.customers AS c ON o.customer_id = c.id;

The default hash join builds one side in memory, so joins every dashboard repeats are cheaper done once at load time. DISTINCT ON works as in Postgres; ClickHouse rewrites it to LIMIT 1 BY.

Step 7: validate before you switch a dashboard

Because postgresql() streams Postgres rows through ClickHouse, you can compute identical aggregates on both sides, hash included. Compare per partition, so a mismatch points at a month:

WITH
    src AS
    (
        SELECT toYYYYMM(created_at) AS month,
               count() AS row_count,
               sum(amount) AS amount_sum,
               groupBitXor(cityHash64(id, status, amount, updated_at)) AS row_hash
        FROM postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret')
        GROUP BY month
    ),
    dst AS
    (
        SELECT toYYYYMM(created_at) AS month,
               count() AS row_count,
               sum(amount) AS amount_sum,
               groupBitXor(cityHash64(id, status, amount, updated_at)) AS row_hash
        FROM analytics.orders FINAL
        GROUP BY month
    )
SELECT month,
       src.row_count AS pg_rows,
       dst.row_count AS ch_rows,
       src.amount_sum = dst.amount_sum AS sums_match,
       src.row_hash = dst.row_hash AS hashes_match
FROM src
FULL OUTER JOIN dst USING (month)
ORDER BY month;

The XOR of row hashes is order-independent, and both sides are hashed by ClickHouse, so they agree whenever the hashed columns have identical types. In our test, a Postgres UPDATE that changed status without bumping updated_at left counts and sums intact and flipped only that month’s hash: exactly the bug a watermark sync produces. To find the rows, compare per-row hashes inside that month:

SELECT s.id
FROM postgresql('pg-replica:5432', 'shop', 'orders', 'ch_reader', 'secret') AS s
WHERE s.created_at >= '2024-04-01' AND s.created_at < '2024-05-01'
  AND cityHash64(s.id, s.status, s.amount, s.updated_at) NOT IN
  (
      SELECT cityHash64(id, status, amount, updated_at)
      FROM analytics.orders FINAL
      WHERE created_at >= '2024-04-01' AND created_at < '2024-05-01'
  );

Before cutover, also compare NULL counts per column, min() and max() of every timestamp and date (zone shifts and clamping show up here), and your ten most-viewed dashboard queries on both engines. Keep the cheap checks running afterwards as data quality tests.

Where Goni fits

Goni is one option that ships this pipeline as a single product. Its Postgres connector loads tables into ClickHouse on a schedule in full or incremental mode, can land late updates and hard deletes in a ReplacingMergeTree target with a current-state view so analysts never write FINAL, and runs row-count and freshness tests, a YAML semantic layer, a SQL IDE and dashboards on the same warehouse. The modeling decisions above still apply.

FAQ

Can ClickHouse replace PostgreSQL?

Not for transactional workloads. ClickHouse does not enforce unique or foreign-key constraints, and it changes data through re-inserts, delete masks and patch parts rather than in-place row updates. The usual architecture keeps PostgreSQL as the system of record and copies the tables you analyze into ClickHouse, which is built for large scans and aggregations.

How do I migrate data from PostgreSQL to ClickHouse?

Write the target tables by hand, using DESCRIBE TABLE postgresql(...) as a starting point for types. Backfill with INSERT INTO ... SELECT ... FROM postgresql(...) in primary-key ranges, keep the copy current with watermark-based incremental loads or CDC, and compare row counts, sums and hashes per partition before switching any dashboard.

Does ClickHouse support UPDATE and DELETE?

Yes, with different costs than Postgres. Lightweight DELETE masks rows and removes them during merges. Lightweight UPDATE writes patch parts and is marked beta. ALTER TABLE ... UPDATE rewrites data parts. For data replicated from Postgres, the standard pattern is ReplacingMergeTree: re-insert the changed row with a higher version and read with FINAL.

Should I use Nullable columns in ClickHouse?

Only where NULL changes the answer. Nullable adds a null mask per column, costs performance and cannot sit in the sort key by default. But leaving it out turns NULLs into 0, empty strings or 1970-01-01, which skews averages and counts. Keep it for measures and dates where unknown matters, and use defaults elsewhere.

How do I keep PostgreSQL and ClickHouse in sync?

Either schedule incremental pulls filtered on an indexed updated_at column, with a periodic anti-join sweep to catch hard deletes, or run change data capture from the Postgres write-ahead log with Debezium, Airbyte or ClickPipes. Incremental pulls are simpler to operate; CDC gives lower latency and captures deletes, at the cost of a replication slot.