ORDER BY, PRIMARY KEY or PARTITION BY expression of a MergeTree table cannot be renamed. If you only need to query it under a different name, add an ALIAS column that refers to it. This is a metadata change: no data is rewritten, the table is not recreated, and filters on the alias use the primary index in the same way as filters on the original column.
The restriction
RENAME COLUMN reference notes this limitation.
Add an ALIAS column
Filters on the alias use the primary index
ClickHouse replaces an alias column with its expression before it plans the query.EXPLAIN indexes = 1 shows that the condition on service_name is applied to the key column svc:
WHERE svc = 'search': 3 of 12 granules are read. The same holds for partition pruning when the alias refers to a partition key column, and for ORDER BY service_name, ts, which reads the data in the order of the sorting key.
What the alias does not change
The stored column keeps its name.svc is still the key column in the table definition, and the new name is an expression over it:
- Both names work in queries, so existing queries that use
svcare not affected. SELECT *does not return alias columns. Name the column in the query, or enable the settingasterisk_include_alias_columns, which makesSELECT *return bothsvcandservice_name.- You cannot insert into an alias column.
INSERT INTO app_logs (service_name, ts, message) ...fails withNo such column service_name in table default.app_logs(NO_SUCH_COLUMN_IN_TABLE). Writers keep usingsvc. - The alias can be removed at any time with
ALTER TABLE app_logs DROP COLUMN service_name, which does not touch the data either.
If the stored column must have the new name
Renaming the stored key column requires a new table. Create it with the column names you want, copy the data withINSERT INTO ... SELECT, and swap the two tables with EXCHANGE TABLES. Stop writes to the table before the copy starts and resume them only after the exchange: rows inserted into the old table in between are not in the new one.