MergeTree table keeps the primary index of its data parts in memory once it is loaded, whether or not anyone still queries the table. Tables left behind by a rename-based migration (sessions_old, events_backup) are the usual case: the new table is small, the old one still holds its whole index. Find such tables with the primary_key_bytes_in_memory column of system.parts, release the memory with SYSTEM UNLOAD PRIMARY KEY, and drop the tables when you no longer need them.
Example
Create a table, fill it, then migrate to a new sorting key by renaming the old table and creating a new one:Why the memory is not released on its own
- A part written by an
INSERTor by a merge keeps the index it has built in memory. - After a server restart, the
primary_key_lazy_loadsetting (enabled by default) loads the index of a part when a query first needs it, so a table that nobody queries starts with nothing loaded. - Once loaded, the index of an active part stays in memory.
RENAME TABLEdoesn’t touch the parts, so the renamed table keeps everything it had loaded.
The index is loaded again on the next use
Unloading is not permanent. A query that filters on the key loads the index again:Clusters and privileges
SYSTEM UNLOAD PRIMARY KEY acts on the server that executes it. On a cluster, run it on every replica or add ON CLUSTER:
system.parts through clusterAllReplicas and add hostName() to the grouping. In ClickHouse Cloud the cluster name is default, as described in Querying across nodes:
SYSTEM UNLOAD PRIMARY KEY privilege, which can be granted for one table:
SYSTEM UNLOAD PRIMARY KEY unloads the primary keys of all tables and needs the privilege globally. The statement is available since ClickHouse 24.4.
Large tables that are still in use
Unloading helps for tables that are not read. For a table that is queried and has a large primary index, look at theuse_primary_key_cache setting instead: with it, the indexes are kept in a shared cache of limited size and are not held by every part. Parts that already hold their index keep it until it is unloaded.