merge table function builds its structure as a union of the columns of all matched tables. For the rows of a table that does not have a column, the column is filled with default values. So when a field moves between tables, for example from a key of a Map to a column of its own, you can either write one expression that takes the value from wherever it is, or add an ALIAS column to the old table so that all tables have the same column.
Example
The old table keeps the status code inside aMap. The new table has a dedicated column:
merge returns the union of their columns. The _table virtual column shows which table a row comes from:
Option 1: one expression over both locations
Because bothattributes and status_code exist in the combined structure, a single expression can choose between them:
Option 2: add an ALIAS column to the old table
Give the old table a column with the new name that is calculated from theMap. Queries can then use the new column name for all tables:
ALIAS column is not stored. Its expression is evaluated when the column is read, so adding it changes only the table metadata.
If you want the values to be stored, declare the column as MATERIALIZED instead. Adding a MATERIALIZED column is also a metadata change: for existing data parts the expression is still calculated on read, and the values are written when parts are merged or when you run ALTER TABLE ... MATERIALIZE COLUMN, which is a mutation that rewrites the column in all parts.
Things to keep in mind
- The second argument of
mergeis a regular expression, not a glob pattern.'^logs_v'matches every table whose name starts withlogs_v. With one argument,merge('^logs_v'), the current database is used. - The union of columns is derived in ClickHouse 25.1 and later. The number of tables examined is limited by the
merge_table_max_tables_to_look_for_schema_inferencesetting (1000 by default). In earlier versions the structure was taken from one of the tables, and a query that refers to a column of another table fails withUNKNOWN_IDENTIFIER. - If a column has different types in different tables, a common type is derived. For example,
UInt16andUInt64giveUInt64. Keep the types of columns with the same name compatible. - A table with the
Mergeengine that is created without a column list derives its structure in the same way, but only once, when it is created. Columns that appear in the underlying tables later are not visible through it until you recreate it. Themergetable function derives the structure for every query.
SELECT for each table layout and combine them with UNION ALL: