> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to query tables with different schemas through the merge table function

> How to read a field that moved from a Map key to its own column when you query old and new tables together with the merge table function or a Merge table.

The [`merge`](https://clickhouse.com/docs/reference/functions/table-functions/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:

```sql theme={null}
CREATE TABLE logs_v1
(
    ts DateTime,
    attributes Map(LowCardinality(String), String),
    message String
)
ENGINE = MergeTree
ORDER BY ts;

CREATE TABLE logs_v2
(
    ts DateTime,
    status_code String,
    message String
)
ENGINE = MergeTree
ORDER BY ts;

INSERT INTO logs_v1 VALUES
    ('2024-09-01 10:00:00', {'status_code': '200', 'host': 'a'}, 'old 1'),
    ('2024-09-01 11:00:00', {'status_code': '500'}, 'old 2');

INSERT INTO logs_v2 VALUES
    ('2024-09-05 10:00:00', '404', 'new 1'),
    ('2024-09-05 11:00:00', '200', 'new 2');
```

Reading both tables through `merge` returns the union of their columns. The `_table` virtual column shows which table a row comes from:

```sql theme={null}
SELECT _table, *
FROM merge(currentDatabase(), '^logs_v')
ORDER BY ts;
```

```text theme={null}
   ┌─_table──┬──────────────────ts─┬─status_code─┬─attributes───────────────────────┬─message─┐
1. │ logs_v1 │ 2024-09-01 10:00:00 │             │ {'status_code':'200','host':'a'} │ old 1   │
2. │ logs_v1 │ 2024-09-01 11:00:00 │             │ {'status_code':'500'}            │ old 2   │
3. │ logs_v2 │ 2024-09-05 10:00:00 │ 404         │ {}                               │ new 1   │
4. │ logs_v2 │ 2024-09-05 11:00:00 │ 200         │ {}                               │ new 2   │
   └─────────┴─────────────────────┴─────────────┴──────────────────────────────────┴─────────┘
```

## 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:

```sql theme={null}
SELECT
    _table,
    ts,
    if(mapContains(attributes, 'status_code'), attributes['status_code'], status_code) AS code
FROM merge(currentDatabase(), '^logs_v')
ORDER BY ts;
```

```text theme={null}
   ┌─_table──┬──────────────────ts─┬─code─┐
1. │ logs_v1 │ 2024-09-01 10:00:00 │ 200  │
2. │ logs_v1 │ 2024-09-01 11:00:00 │ 500  │
3. │ logs_v2 │ 2024-09-05 10:00:00 │ 404  │
4. │ logs_v2 │ 2024-09-05 11:00:00 │ 200  │
   └─────────┴─────────────────────┴──────┘
```

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:

```sql theme={null}
ALTER TABLE logs_v1
    ADD COLUMN status_code String ALIAS attributes['status_code'];

SELECT _table, ts, status_code
FROM merge(currentDatabase(), '^logs_v')
WHERE status_code = '200'
ORDER BY ts;
```

```text theme={null}
   ┌─_table──┬──────────────────ts─┬─status_code─┐
1. │ logs_v1 │ 2024-09-01 10:00:00 │ 200         │
2. │ logs_v2 │ 2024-09-05 11:00:00 │ 200         │
   └─────────┴─────────────────────┴─────────────┘
```

An [`ALIAS`](https://clickhouse.com/docs/reference/statements/create/table#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`](https://clickhouse.com/docs/reference/statements/create/table#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`](https://clickhouse.com/docs/reference/statements/alter/column#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`](https://clickhouse.com/docs/reference/settings/session-settings/other#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`](https://clickhouse.com/docs/reference/engines/table-engines/special/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`:

```sql theme={null}
SELECT *
FROM
(
    SELECT 'logs_v1' AS source, ts, attributes['status_code'] AS code
    FROM logs_v1
    UNION ALL
    SELECT 'logs_v2' AS source, ts, status_code AS code
    FROM logs_v2
)
ORDER BY ts;
```

```text theme={null}
   ┌─source──┬──────────────────ts─┬─code─┐
1. │ logs_v1 │ 2024-09-01 10:00:00 │ 200  │
2. │ logs_v1 │ 2024-09-01 11:00:00 │ 500  │
3. │ logs_v2 │ 2024-09-05 10:00:00 │ 404  │
4. │ logs_v2 │ 2024-09-05 11:00:00 │ 200  │
   └─────────┴─────────────────────┴──────┘
```
