Overview

A projection is a hidden, automatically maintained copy of (part of) a table, stored inside each data part, with a different sort order or pre-aggregated. The optimizer picks it transparently when it can answer a query cheaper. It is ClickHouse’s analogue of a secondary index plus a materialised aggregate, without a separate table (ch-materialized-views are explicit; projections are implicit).

Core concepts

  • Two flavours: a re-sorted projection (SELECT * ORDER BY other_col) for filters on another column, and an aggregating projection (SELECT key, sum(x) GROUP BY key).
  • Created with ALTER TABLE ... ADD PROJECTION name (SELECT ...); existing parts need MATERIALIZE PROJECTION. New inserts and merges maintain it.
  • Controlled by optimize_use_projections (on by default). Inspect system.projection_parts and EXPLAIN.
  • Cost: extra storage and extra work on every insert and merge; projections do not support every table engine feature (for example some deduplicating engines have restrictions).

Worked example

events_a is ordered by (country, event_type, user_id), so filtering on url scans everything. Add an aggregating projection:

ALTER TABLE events_a ADD PROJECTION p_url (SELECT url, count() AS c, sum(amount) AS s GROUP BY url);
ALTER TABLE events_a MATERIALIZE PROJECTION p_url SETTINGS mutations_sync = 2;
 
SELECT url, sum(amount) FROM events_a WHERE url = '/p/77' GROUP BY url;
optimize_use_projectionsRows readBytes read
05,000,00070.8 MiB
125,000629 KiB

The projection occupies 274 KiB on disk (system.projection_parts), because it stores only one row per distinct url per part. The query went from a full scan to reading the projection’s sorted aggregates.

Pitfalls and production notes

  • A projection speeds up only queries it matches; verify with EXPLAIN that it is used.
  • Every insert pays for building each projection; add them selectively on proven slow, frequent queries.
  • Alternatives: change the sorting key, a materialized view into a different table, or a skipping index (ch-skipping-indexes).
  • A materialised view can feed any table engine and be queried directly; a projection is invisible and tied to the base table.
  • Contaminated benchmarks: after adding a projection, other tests on the same table may use it (I noticed this when a WHERE url experiment read only 25,000 rows).

Practice questions

  1. When would you prefer a materialized view over a projection?
  2. What happens to a projection during a merge?
  3. How can you tell whether a query used a projection?

References

  • ClickHouse documentation, Projections

ch-materialized-views · ch-sorting-key-sparse-index · ch-skipping-indexes