Skip to main content
The 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 a Map. The new table has a dedicated column:
Reading both tables through 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 both attributes and status_code exist in the combined structure, a single expression can choose between them:
Nothing changes in the tables, but every query has to repeat the expression.

Option 2: add an ALIAS column to the old table

Give the old table a column with the new name that is calculated from the Map. Queries can then use the new column name for all tables:
An 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 merge is a regular expression, not a glob pattern. '^logs_v' matches every table whose name starts with logs_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_inference setting (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 with UNKNOWN_IDENTIFIER.
  • If a column has different types in different tables, a common type is derived. For example, UInt16 and UInt64 give UInt64. Keep the types of columns with the same name compatible.
  • A table with the Merge engine 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. The merge table function derives the structure for every query.
On a version where the union of columns is not available, write one SELECT for each table layout and combine them with UNION ALL: