DB::Exception: Cannot alter column 'col' because it is used in the primary key
0 reputation · 02 Dec 2020, 03:22 UTC
0 reputation · 02 Dec 2020, 03:22 UTC
When executing ALTER TABLE t MODIFY COLUMN col TYPE String on a MergeTree‑family table that already defines col in its primary key, ClickHouse throws the error DB::Exception: Cannot alter column 'col' because it is used in the primary key. The operation is rejected before any data mutation occurs.
The absence of a clear path to alter primary key columns raises a design question: should ClickHouse allow primary key changes through ALTER TABLE with automatic data reorganization, or is recreating the table the only viable approach?
ALTER TABLE framework?33775 reputation · 02 Dec 2020, 10:00 UTC
The error DB::Exception: Cannot alter column 'col' because it is used in the primary key is expected behavior. ClickHouse deliberately rejects ALTER TABLE ... MODIFY COLUMN on any column that participates in the primary (sorting) key of a MergeTree-family table. No stable release, including the 23.x line and later, supports in-place primary key mutation.
ReplacingMergeTree version column or SummingMergeTree columns).
CREATE TABLE t_new (
col String,
...
) ENGINE = MergeTree()
ORDER BY (col, ...);
INSERT INTO t_new SELECT * FROM t;
SELECT count() FROM t;
SELECT count() FROM t_new;
SELECT * FROM system.parts WHERE table = 't_new' FORMAT Vertical;
RENAME or EXCHANGE TABLES (the latter preserves UUIDs for replicated tables).
RENAME TABLE t TO t_old, t_new TO t;
DROP TABLE t_old;
EXCHANGE TABLES to keep UUIDs consistent.ALTER TABLE UPDATE/DELETE rewrites values but never changes the primary key definition, so they cannot bypass this restriction.What is the exact output of SELECT version()? A small number of recent experimental builds have discussed incremental primary key rewrite, but none are in general availability. Knowing your precise version confirms whether any new alter capability exists for your deployment.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.