Skip to main content
A column that is used in the 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

The RENAME COLUMN reference notes this limitation.

Add an ALIAS column

The new name can be used anywhere in a query:

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:
The plan is identical to the plan of the same query with 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:
This has a few consequences:
  • Both names work in queries, so existing queries that use svc are not affected.
  • SELECT * does not return alias columns. Name the column in the query, or enable the setting asterisk_include_alias_columns, which makes SELECT * return both svc and service_name.
  • You cannot insert into an alias column. INSERT INTO app_logs (service_name, ts, message) ... fails with No such column service_name in table default.app_logs (NO_SUCH_COLUMN_IN_TABLE). Writers keep using svc.
  • 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 with INSERT 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.