MySQL to ClickHouse: a migration and sync playbook
Keep MySQL for transactions and move the analytics. Type mapping, zero dates, collations, a batched backfill with mysql(), binlog CDC settings, the query rewrites that change answers, and checks.
To move analytics from MySQL to ClickHouse, keep MySQL as the system of record and copy only the tables you report on: map each MySQL type deliberately, expose awkward columns through a MySQL view, backfill in primary-key batches with ClickHouse’s mysql() table function, keep the copy current with a watermark pull or binlog-based change data capture, and compare per-partition counts and hashes before any dashboard switches. The shared mechanics (sort keys, ReplacingMergeTree, update and delete patterns) are the same as for Postgres, and our Postgres to ClickHouse playbook covers them in depth. This post covers what is different about MySQL, and that is where most migration bugs hide: 0000-00-00 dates become 1970, TIMESTAMP values shift with the session time zone, case-insensitive collations turn into case-sensitive comparisons, and InnoDB foreign-key cascades never reach the binary log. Every example below was run against MySQL 8.4.13 and ClickHouse 26.10.
MySQL vs ClickHouse for analytics: when to move
ClickHouse sits next to MySQL; it does not replace it. InnoDB is built for short transactions and point reads by primary key. A dashboard query that scans months of orders and aggregates a few columns reads every row of every page it touches, competes with the application for the buffer pool, and gets slower as the table grows. ClickHouse stores each column separately and skips blocks of rows using a sparse index on its sort key, which is why the same aggregation usually returns much faster.
Move when reporting queries keep slowing down after you have tuned indexes and added a replica, when summary tables multiply to keep dashboards responsive, or when analysts are told not to run queries during business hours. Stay when the heaviest report already finishes acceptably on a replica, or when reports must reflect a commit instantly.
Step 1: map MySQL types to ClickHouse
Ask ClickHouse what it infers before writing DDL:
DESCRIBE TABLE mysql('mysql-replica:3306', 'shop', 'orders', 'ch_reader', 'secret')
SETTINGS describe_compact_output = 1;
The inference is controlled by mysql_datatypes_support_level, which in 26.10 defaults to decimal,datetime64,date2Date32,geometry. Nullable source columns arrive as Nullable(T). Treat the output as a draft:
| MySQL | mysql() infers (26.10) | Recommended target | Watch out for |
|---|---|---|---|
TINYINT, SMALLINT, INT, BIGINT | Int8, Int16, Int32, Int64 | Same | MEDIUMINT arrives as Int32 |
... UNSIGNED | UInt8 to UInt64 | Same | Subtraction semantics differ (Step 5) |
TINYINT(1), BOOLEAN | Int8 | Bool | Check that only 0 and 1 occur |
DECIMAL(p, s) | Decimal(p, s) | Same | Up to DECIMAL(65, 30) maps directly |
FLOAT, DOUBLE | Float32, Float64 | Same | Never for money |
VARCHAR, TEXT, BLOB | String | String or LowCardinality(String) | Collation is lost (below) |
ENUM(...) | String | LowCardinality(String) or Enum8 | Enum8 rejects new values until altered |
SET(...) | String ('gift,promo') | Array(LowCardinality(String)) | Split it on load |
JSON | String | JSON or String | JSON exposes paths as subcolumns |
BINARY(16) (UUIDs) | FixedString(16) | UUID or FixedString(16) | Convert byte order deliberately |
BIT(n) | UInt64 | Same | |
YEAR | String | UInt16 | |
TIME | String | Int32 seconds | Range is -838:59:59 to 838:59:59, so it is a duration |
DATE | Date32 | Date32, or Date for 1970 to 2149 | |
DATETIME | DateTime64(0) | DateTime('UTC') | No zone conversion on read |
TIMESTAMP(6) | DateTime64(6) | DateTime64(6, 'UTC') | Converted to the session zone on read (below) |
Zero dates become 1970-01-01
MySQL 8.4 forbids 0000-00-00 under the default sql_mode (NO_ZERO_DATE is in it), but tables created under older modes still carry them. In our test, a DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' column came through mysql() as 1970-01-01 00:00:00, a real-looking date that silently corrupts any “days since” metric. Convert zero dates to NULL on the MySQL side, where you can still tell them apart.
TIMESTAMP shifts with the session time zone
MySQL stores TIMESTAMP in UTC and converts it to the session time_zone on output; DATETIME is stored and returned as written. With the server’s global time_zone set to +02:00, every TIMESTAMP we read through mysql() came back two hours later than the UTC value. Check SELECT @@global.time_zone, @@system_time_zone on the source before the backfill, and fix the column’s zone in the ClickHouse DDL.
Collations do not survive the copy
The default MySQL 8.4 collation, utf8mb4_0900_ai_ci, is accent- and case-insensitive. ClickHouse String comparisons are byte-wise. Rows that MySQL treats as one value become two in ClickHouse, which changes filters, GROUP BY and distinct counts (examples in Step 5). Decide per column whether to normalize on load, for example storing lowerUTF8(email), or to normalize in queries. Case folding does not cover accents: ai also makes é equal e in MySQL, and nothing in ClickHouse does that implicitly.
A view on the MySQL side
The cleanest place to fix types is a view in MySQL that the ClickHouse reader selects from:
-- Run in MySQL
CREATE VIEW shop.orders_export AS
SELECT id, customer_id, status, tags, is_test, amount, rating, email, attrs,
TIME_TO_SEC(prep_time) AS prep_secs,
created_at, updated_at, shipped_at,
CAST(NULLIF(legacy_date, 0) AS DATETIME) AS legacy_date
FROM shop.orders;
CREATE USER 'ch_reader'@'%' IDENTIFIED BY 'secret';
GRANT SELECT ON shop.* TO 'ch_reader'@'%';
Compare with 0, not with the string '0000-00-00 00:00:00': under the default 8.4 sql_mode, that literal makes every read of the view fail with error 1525, “Incorrect DATETIME value”. The CAST matters too: without it, MySQL types the NULLIF result as a string and ClickHouse infers Nullable(String). Simple views like this one are merged into the outer query, and EXPLAIN confirmed that a filter on updated_at still used its index.
Step 2: create the target table
The rules from the Postgres playbook apply unchanged: an ORDER BY built for your filters rather than the MySQL primary key, monthly partitions at most, and a ReplacingMergeTree with a version column and a delete flag for any table that receives updates.
CREATE TABLE analytics.orders
(
id UInt64,
customer_id UInt32,
status LowCardinality(String),
tags Array(LowCardinality(String)),
is_test Bool,
amount Decimal(12, 2),
rating Nullable(Float32),
email String,
attrs JSON,
prep_secs Nullable(Int32),
created_at DateTime64(6, 'UTC'),
updated_at DateTime64(6, 'UTC'),
shipped_at Nullable(DateTime('UTC')),
legacy_date Nullable(DateTime('UTC')),
is_deleted UInt8 DEFAULT 0
)
ENGINE = ReplacingMergeTree(updated_at, is_deleted)
PARTITION BY toYYYYMM(created_at)
ORDER BY (customer_id, created_at, id);
ORDER BY and partition columns must never change for a given row, because they are how duplicates are found. Read with FINAL (or through a view that applies it) to get current state.
Step 3: backfill with the mysql() table function
Per the mysql() table function docs, simple comparisons (=, !=, >, >=, <, <=) run on the MySQL server and everything else runs in ClickHouse after the rows arrive. In our 26.10 tests IN was pushed down as well, but LIKE and functions such as lower() were not, so those filters read the whole table. MySQL’s general log showed the batch range arriving intact: SELECT ... FROM shop.orders_export WHERE (id > 0) AND (id <= 100000).
INSERT INTO analytics.orders
(id, customer_id, status, tags, is_test, amount, rating, email, attrs,
prep_secs, created_at, updated_at, shipped_at, legacy_date)
SELECT id, customer_id, status,
arrayFilter(t -> t != '', splitByChar(',', ifNull(tags, ''))),
is_test, amount, rating, email, ifNull(attrs, '{}'),
prep_secs, created_at, updated_at, shipped_at, legacy_date
FROM mysql('mysql-replica:3306', 'shop', 'orders_export', 'ch_reader', 'secret')
WHERE id > 0 AND id <= 100000;
The arrayFilter matters too: splitByChar on an empty SET value returns [''], not an empty array. Loop over id ranges from a script, sized so a batch finishes in a few minutes. Read from a replica: a long consistent read keeps an old InnoDB read view open, which holds back purge on a busy primary. On ReplacingMergeTree, a retried batch only adds duplicates that FINAL resolves.
Since ClickHouse 26.7, the table argument can also be a query passed to MySQL verbatim, mysql(..., query('SELECT ...'), ...), if you cannot create views on the source. The docs note that an outer WHERE is not pushed into a passed query, so put the batch range inside it. For production, the docs recommend named collections over inline credentials.
Step 4: keep it in sync, by watermark or by binlog
Watermark pulls
MySQL makes the watermark column easy: updated_at TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) maintains itself. Index it, then pull on a schedule with an overlap:
INSERT INTO analytics.orders
(id, customer_id, status, tags, is_test, amount, rating, email, attrs,
prep_secs, created_at, updated_at, shipped_at, legacy_date)
SELECT id, customer_id, status,
arrayFilter(t -> t != '', splitByChar(',', ifNull(tags, ''))),
is_test, amount, rating, email, ifNull(attrs, '{}'),
prep_secs, created_at, updated_at, shipped_at, legacy_date
FROM mysql('mysql-replica:3306', 'shop', 'orders_export', 'ch_reader', 'secret')
WHERE updated_at > (SELECT max(updated_at) - INTERVAL 15 MINUTE
FROM analytics.orders WHERE is_deleted = 0);
ClickHouse evaluates the subquery first and pushes the result down as a literal; the general log showed WHERE updated_at > '2026-03-01 07:45:00.000000'. Two caveats: ON UPDATE does not fire when a statement sets updated_at explicitly, which some bulk jobs do, and a watermark never sees hard deletes. Sweep for those nightly with DELETE FROM analytics.orders WHERE id NOT IN (SELECT id FROM mysql(...)).
Binlog change data capture
CDC tools read the MySQL binary log and land every insert, update and delete as a versioned row. MySQL 8.4 already logs in the right shape for most of them; check these before you pick a tool:
| Setting | MySQL 8.4 default | What CDC tools need |
|---|---|---|
log_bin | On | On |
binlog_format | ROW | ROW |
binlog_row_image | FULL | FULL |
binlog_row_metadata | MINIMAL | FULL for ClickPipes |
gtid_mode | OFF | ON recommended; survives failover |
binlog_expire_logs_seconds | 2592000 (30 days) | Long enough to cover any pipeline outage |
The Debezium MySQL connector needs ROW format and FULL row images, plus SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT, and its initial snapshot takes a global read lock briefly (or table locks on RDS and Aurora). ClickPipes MySQL CDC is generally available in ClickHouse Cloud and supports self-hosted MySQL, RDS, Aurora, Cloud SQL and MariaDB. Airbyte reads the binlog too. We compare the three in CDC to ClickHouse: Debezium, Airbyte, ClickPipes.
Two MySQL-specific warnings. First, many older guides recommend ClickHouse’s MaterializedMySQL database engine. It is gone: ClickHouse 26.10 rejects it as an unknown database engine, even with the old experimental setting enabled. Second, InnoDB foreign-key cascades are invisible to CDC. In our test, DELETE FROM customers WHERE id = 1 cascaded to two rows in customer_notes, but the binlog held a single row event, for customers. The MySQL 8.4 manual says it directly: cascading deletes are handled inside InnoDB, so “none of the changes are logged”. A replica re-applies the cascade itself; a CDC tool feeding ClickHouse cannot. Since MySQL 9.6, the server handles foreign keys in the SQL layer by default, so those cascades do write child-table row events. On 8.4, replicate child deletes with an anti-join sweep, or delete children explicitly in the application.
Step 5: rewrite the queries that change meaning
These all ran on both engines with the same data and returned different answers:
| Query | MySQL 8.4 | ClickHouse 26.10 | Rewrite |
|---|---|---|---|
WHERE email = 'ana@example.com' | Matches Ana@Example.com too | Exact bytes only | lowerUTF8(email) = lowerUTF8(...), or normalize on load |
GROUP BY email | One group per case-folded value | One group per spelling | Group by lowerUTF8(email) |
COUNT(DISTINCT email) | Ana@... and ana@... count once | They count twice | uniqExact(lowerUTF8(email)) |
GROUP_CONCAT(x) | Comma-separated | No separator | groupConcat(x, ',') |
0.1 + 0.2 = 0.3 | 1; literals are exact decimals | 0; literals are Float64 | Cast to Decimal |
7 / 2 | 3.5000 (decimal) | 3.5 (Float64) | DIV works in both for integers |
a - b on UNSIGNED columns, b > a | Error 1690, out of range | -2 (result is Int64) | Decide which behaviour you want |
ORDER BY x with NULLs | NULLs first | NULLs last | NULLS FIRST explicitly |
DATE('2026-02-30') | NULL with a warning | toDate('2026-02-30') returns 2026-03-02 | Validate dates with parseDateTimeOrNull |
DATE_FORMAT(ts, '%D %c %r') | 5th 3 02:07:09 PM | 03/05/26 03 02:07 PM | Stick to %Y %m %d %H %i %s, which match in both |
Plenty carries over unchanged: backtick identifiers, IFNULL, LIMIT offset, count and DIV, and DATE_FORMAT exists with the common specifiers matching. That familiarity is the risk: the queries that break are the ones that run without an error.
Step 6: validate before you switch a dashboard
Because mysql() streams source rows through ClickHouse, both sides of a comparison are computed by the same engine, hashes included:
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 mysql('mysql-replica:3306', 'shop', 'orders_export', '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 mysql_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;
A month whose hash differs while counts and sums match usually means an update that did not bump updated_at; the Postgres playbook shows how to narrow it to rows. For MySQL, add three checks: count rows where any date equals 1970-01-01, compare min() and max() of every TIMESTAMP column against UNIX_TIMESTAMP() computed in MySQL itself to catch a zone shift (a comparison through mysql() reads the same shifted values that were loaded), and compare COUNT(DISTINCT) on collated text columns to see where case folding will change reports. Keep the cheap checks running as data quality tests.
Where Goni fits
If you would rather not run this pipeline yourself, Goni is one option. Its MySQL, MariaDB and Aurora MySQL connectors load tables into ClickHouse on a schedule, in full mode or in incremental mode on a watermark column, and the same product adds freshness and data quality tests, a YAML semantic layer, a SQL IDE and dashboards on that warehouse. The trade-offs: it loads in scheduled batches rather than streaming the binlog, ClickHouse is the only warehouse it queries, and the type and collation decisions above are still yours to make.
FAQ
Can ClickHouse replace MySQL?
Not for transactional workloads. ClickHouse does not enforce unique or foreign-key constraints and changes rows through re-inserts, delete masks and part rewrites rather than in-place updates. The usual architecture keeps MySQL 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 MySQL to ClickHouse?
Create the target tables by hand, using DESCRIBE TABLE mysql(...) as a starting point for types. Fix zero dates and TIME columns in a MySQL view, split SET values on load, backfill with INSERT INTO ... SELECT ... FROM mysql(...) in primary-key ranges, keep it current with watermark pulls or CDC, and compare counts and hashes per partition.
Is MaterializedMySQL still available in ClickHouse?
No. ClickHouse 26.10 rejects ENGINE = MaterializedMySQL as an unknown database engine, even with allow_experimental_database_materialized_mysql enabled. For continuous replication, use a binlog-based CDC tool such as Debezium with a Kafka sink, Airbyte, or ClickPipes in ClickHouse Cloud, or schedule incremental pulls through the mysql() table function.
How do I replicate MySQL to ClickHouse in real time?
Use change data capture from the MySQL binary log. Enable row-based logging with full row images, turn on GTIDs so the pipeline survives failover, and keep binlogs long enough to cover an outage. Debezium, Airbyte and ClickPipes then land each change in ClickHouse, usually into a ReplacingMergeTree table keyed on the source primary key.
Why does ClickHouse return different results than MySQL for the same query?
Usually because of collations, types or NULL handling. MySQL’s default collation compares text case-insensitively and ClickHouse compares bytes, so filters, groups and distinct counts change. Decimal literals become floats, NULLs sort last instead of first, and zero dates arrive as 1970-01-01. Compare your most-used queries on both engines before cutover.