Skip to main content
A materialized view matches the columns returned by its SELECT to the columns of the target table by name, not by position. When both joined tables have a column with the same name and you select it from the right-hand table, the result column is called o.order_id, not order_id. No target column has that name, so the target column is filled with the default value of its type: an empty string, 0 or 1970-01-01. To fix it, give every column of the SELECT an alias with AS.

Reproduce the problem

orders and payments both have the columns order_id and created_at. The view should store each payment together with the id, date and customer of its order:
What happens next depends on the version. Since ClickHouse 25.4, the CREATE MATERIALIZED VIEW statement is rejected, and the message names the fix:
Before 25.4, or with the setting allow_materialized_view_with_bad_select enabled, the view is created without an error. The check runs only when a view is created, so a view like this one keeps working the same way after an upgrade. To follow the rest of the example on a current version, run SET allow_materialized_view_with_bad_select = 1 before the CREATE MATERIALIZED VIEW statement and set it back to 0 afterwards. Every insert into payments then writes a row with default values in order_id and created_at:

Why this happens

Run the SELECT of the view on its own and look at the column names of the result:
The values are correct, but two columns are named o.order_id and o.created_at. order_id and created_at exist in both tables, so the columns taken from the right-hand table keep their qualifier in the result (p.order_id would be named order_id). The view ignores a result column that has no counterpart in the target table, and fills a target column that the result does not provide with its default value, even if the column is not Nullable.

Fix the view

Add an alias to every column, so that the names no longer depend on how ClickHouse names expressions. You can change the query of an existing view with ALTER TABLE ... MODIFY QUERY:
New rows are correct. The view does not rewrite the rows it wrote before the fix: delete them from the target table and insert the result of the corrected SELECT for them.

What else to check

  • ALTER TABLE ... MODIFY QUERY does not perform the check that CREATE MATERIALIZED VIEW does. It accepts a query whose column names do not match the target table, and the view then writes default values again. Run the new SELECT and compare its column names with the target table before you apply it.
  • A target column that the SELECT does not return at all is filled with its default value without any error. This is by design: it lets you add a column to the target table before you change the view.