Materialized Views
A materialized view stores the results of a query in a Paimon table. Use it to persist a frequently queried projection, such as values extracted from a VARIANT column.
Use Spark 4.1, 4.2, or 4.3 with the matching Paimon Spark connector,
a Paimon catalog, and the Paimon Spark SQL extensions.
The query can project or deduplicate columns and deterministic Spark built-in expressions from one
Data Evolution table, join Data Evolution inputs on
equal keys, or aggregate their results with an optional GROUP BY. It can also combine
projections and filters from multiple Data Evolution tables with set operations, expand
rows with built-in generators, and use Spark window functions.
Nonrecursive WITH clauses can compose these queries. A WHERE clause can use
supported predicate subqueries.
Use the current branch head of each source table or materialized view. Unqualified source names
resolve in the view's database. Qualify a source name when it is in another database or catalog.
Create a materialized view
CREATE MATERIALIZED VIEW [IF NOT EXISTS] view_name AS query;
The statement creates an unpartitioned Data Evolution backing table with
type=materialized-table and deletion vectors, then populates it synchronously.
The backing table inherits the catalog's file format. It supports Parquet, ROW, ORC,
and Avro. Paimon uses Parquet by default.
In Spark, the view exposes the columns of the SELECT.
Paimon stores the query in the backing table's materialized-table.definition-query
property. For a plain SELECT over one source table with no WHERE or DISTINCT, the backing
files preserve source row IDs through their firstRowId and row count. Deletion vectors hide
positions of deleted source rows. Filtered projections, distinct projections, joins,
aggregates, and windows allocate target row IDs.
CREATE TABLE paimon.default.events (
id INT,
payload VARIANT,
enabled BOOLEAN
) TBLPROPERTIES (
'row-tracking.enabled' = 'true',
'data-evolution.enabled' = 'true',
'deletion-vectors.enabled' = 'true'
);
INSERT INTO paimon.default.events VALUES
(1, parse_json('{"pose":[10.5]}'), true),
(2, parse_json('{"pose":[20.5]}'), true),
(3, parse_json('{"pose":[30.5]}'), false);
CREATE MATERIALIZED VIEW paimon.default.pose_mv AS
SELECT id, try_variant_get(payload, '$.pose', 'array<float>') AS pose
FROM events
WHERE enabled;
SELECT * FROM paimon.default.pose_mv ORDER BY id;
Refresh a materialized view
UPDATE paimon.default.events SET enabled = true WHERE id = 3;
DELETE FROM paimon.default.events WHERE id = 2;
REFRESH MATERIALIZED VIEW paimon.default.pose_mv;
SELECT * FROM paimon.default.pose_mv ORDER BY id;
For a single-source projection without DISTINCT, the refresh pins the latest source snapshot
and evaluates changes on the Spark driver. A query without WHERE rebuilds affected target
row-ID ranges. A filtered query evaluates the affected rows in the previous and current source
snapshots, then applies the change in the count of each projected result. Both paths handle
partial-column updates and deletion-vector changes. Paimon commits the refreshed data and source
progress in the same target snapshot. An unchanged source snapshot keeps the current target
snapshot when it uses the current read schema.
Paimon can rebuild the view when the source read schema changes, the required source history
is unavailable, or filtered changes exceed the in-memory budget.
Run refreshes for a given view one at a time and use the same SQL session settings, such as
the session time zone, for creation and refresh. Use DROP TABLE to remove the
materialization. Recreate the view to change its query definition.
Recreate the view after a source rollback that reuses snapshot IDs or a rename that makes the
definition resolve to different tables.
Refresh a dependent materialized view
Use an existing Paimon materialized view as a source for another view. For example, maintain event counts by ID and use the counts to maintain a top-K result.
CREATE MATERIALIZED VIEW paimon.default.counts_by_id AS
SELECT id, COUNT(*) AS n FROM events GROUP BY id;
CREATE MATERIALIZED VIEW paimon.default.top_event_ids AS
SELECT id, n FROM counts_by_id ORDER BY n DESC, id LIMIT 10;
REFRESH MATERIALIZED VIEW paimon.default.counts_by_id;
REFRESH MATERIALIZED VIEW paimon.default.top_event_ids;
Each refresh reads the committed snapshots of its direct sources. Refresh upstream views first to include changes to their inputs. Paimon commits the consumed source snapshot IDs with the dependent view's results. Keep the upstream snapshot history between refreshes for incremental evaluation. If that history expires, Paimon can rebuild the dependent view from the current pinned upstream snapshot.
When a source schema change or missing snapshot prevents incremental planning for an eligible
grouped view, Paimon reevaluates the query and can publish just the changed result rows. The view
must project all grouping keys and use supported scalar output types. Eligible views can use
HAVING and rename keys through outer projections. Unchanged groups retain their row IDs.
Paimon can fall back to an overwrite if the previous result is unavailable or the row changes
exceed the refresh budget.
Combine projections with UNION ALL
CREATE MATERIALIZED VIEW paimon.default.all_events AS
SELECT id, payload FROM events WHERE enabled
UNION ALL
SELECT id, payload FROM archived_events WHERE enabled;
REFRESH MATERIALIZED VIEW paimon.default.all_events;
Both inputs are Data Evolution tables. Paimon evaluates the affected row-ID ranges in each source at its previous and current snapshots. Spark applies the difference in result multiplicity across the branches, so identical copies that move between sources can retain their existing target rows. Paimon commits every source position with the refreshed data in one snapshot. It can rebuild if history is unavailable, the read schema changes, or the set of source tables changes.
Distinct projections
CREATE MATERIALIZED VIEW paimon.default.enabled_event_ids AS
SELECT DISTINCT id FROM events WHERE enabled;
REFRESH MATERIALIZED VIEW paimon.default.enabled_event_ids;
For a distinct projection over one Data Evolution table, Spark evaluates projected tuples in the changed row-ID ranges. Paimon inserts a tuple when its first occurrence appears and removes it when its last occurrence disappears. Spark compares NULL values as equal for this membership check. When a few changed tuples have physical keys, file statistics can prune the search for surviving copies. Spark filters the surviving tuples by the candidate keys before the shuffle. The target rows for unchanged tuples keep their row IDs.
Single-source distinct projections of boolean, integer, date, decimal, and timestamp values can refresh incrementally. Other types on this path use full Spark evaluation. Compound distinct queries can keep candidate tuples and survivor checks in distributed Spark plans.
Set operations and row generators
Incremental plans can combine UNION ALL, UNION DISTINCT, INTERSECT, and EXCEPT,
including ALL variants for intersection and difference. Refresh applies Spark's tuple
equality and preserves the number of copies specified by each set operator.
For intersection and difference, refresh reevaluates the affected tuples in both inputs.
Tuples with types outside the incremental comparison path use a full refresh.
UNPIVOT and built-in generators such as explode, inline, and variant_explode can
also participate. A lateral built-in generator can expand each affected row independently.
Join Data Evolution inputs
Supported join types are INNER, LEFT OUTER, RIGHT OUTER, FULL OUTER,
LEFT SEMI, and LEFT ANTI. Join conditions can combine = and <=> predicates with
AND. Each predicate compares a column from each input, with both columns of the same
supported type. Key types include integral types, booleans, dates, decimals, timestamps,
and strings with binary collation. A join input can be a Data Evolution table or a
derived query using supported projections, filters, set operations, row generators, and
equality joins. The SELECT can omit the join keys, and the result can contain duplicate
rows.
The following view joins events and annotations on their ID and category columns.
CREATE MATERIALIZED VIEW paimon.default.annotated_events AS
SELECT e.id, a.label
FROM events AS e LEFT OUTER JOIN annotations AS a
ON e.id = a.event_id AND e.category <=> a.category
WHERE e.enabled;
REFRESH MATERIALIZED VIEW paimon.default.annotated_events;
Paimon collects affected key tuples from changed row-ID ranges in the previous and current source snapshots. For an eligible inner join, every changed pair includes a changed row from at least one side. Spark processes the two sides separately and assigns pairs that change on both sides to one input. This avoids replaying pairs of unchanged rows at the same key. For an eligible full outer join of two tables, Spark also updates unchanged rows whose key gains its first match or loses its last. Semi and anti joins can use the same first-match and last-match checks when only their right input changes.
Refresh preserves the NULL semantics of = and <=> and applies the WHERE to
the join results. When reading keys separately could change the evaluation of an
input expression, refresh runs the original query at the current pinned source
snapshots.
Paimon can prune source files by affected keys when file comparisons match Spark
semantics. A mixed key can use a bounded sample of its fixed-width columns for file
pruning. Spark compares the full key and can keep larger key sets distributed. Refresh
applies the change in multiplicity of each projected row and commits every source position with the refreshed
data in one target snapshot. A source without a snapshot is treated as empty. Refresh
can rebuild the view if history is missing, the read schema changes, or the result
changes exceed the refresh budget. The driver budget also respects
spark.driver.maxResultSize.
Use common table expressions and predicate subqueries
Use nonrecursive WITH clauses to name intermediate results. Spark resolves CTE
names using the session's name resolution rules and inlines the CTEs. The view tracks
the Data Evolution tables referenced by the resulting query. Multiple references to
the same source share one position.
Use EXISTS, NOT EXISTS, IN, and NOT IN as predicates in WHERE. You can
combine them with other predicates using AND.
CREATE MATERIALIZED VIEW paimon.default.unannotated_events AS
WITH active AS (SELECT id FROM events WHERE enabled)
SELECT id
FROM active
WHERE id NOT IN (SELECT event_id FROM annotations);
REFRESH MATERIALIZED VIEW paimon.default.unannotated_events;
When Spark can lower a predicate to supported equalities, refresh uses the same
affected-key plan as a semi or anti join. Refresh pins the original query, including
its subqueries, for shapes that require full evaluation. Examples include tuple
NOT IN, correlated NOT IN with an additional join condition, and subquery
expressions whose evaluation depends on an input filter.
For an eligible single-column NOT IN, refresh checks whether the right result is
empty, contains a NULL, or has only non-NULL keys. With non-NULL keys on the right,
the affected keys determine which non-NULL left rows change. A duplicate right key
can leave membership unchanged. When the right result becomes empty or nonempty,
refresh also includes NULL left keys. A change between a NULL-blocked and an
unblocked result can affect all left rows. If a right-side NULL blocks the entire
view, refresh can clear the result through an empty overwrite and advance both
source positions. When the last blocking NULL disappears, refresh populates the
view from the current inputs.
Refresh window functions
Use inline OVER clauses or named WINDOW specifications. The following view
keeps the two highest-scoring events in each category.
CREATE MATERIALIZED VIEW paimon.default.top_events_by_category AS
WITH ranked AS (
SELECT id, score, row_number() OVER (
PARTITION BY category ORDER BY score DESC, id
) AS position
FROM scored_events
)
SELECT id, score FROM ranked WHERE position <= 2;
REFRESH MATERIALIZED VIEW paimon.default.top_events_by_category;
For eligible PARTITION BY windows, Spark recomputes the partitions touched by
changes in the previous and current source snapshots. A row moving between
partitions affects both partitions. Include a unique tie breaker in ORDER BY
when a function such as row_number depends on the order of rows with equal keys.
Rank functions such as rank and dense_rank can refresh partitions with ties.
Without PARTITION BY, a ROWS BETWEEN CURRENT ROW AND CURRENT ROW frame can
refresh row by row. For COUNT, supported MIN and MAX, and sums of
TINYINT, SMALLINT, or INT, a RANGE BETWEEN CURRENT ROW AND CURRENT ROW
frame can refresh the groups sharing each changed ORDER BY tuple, including NULL keys. With a
single INT or BIGINT order column, supported finite ROWS and RANGE frames
can use file statistics to scan the affected frames and their required neighbors.
Fixed-offset LAG and LEAD with RESPECT NULLS can use the same neighbor scan.
Unchanged results keep their target row IDs.
Refresh runs the original query at the current pinned snapshots when it cannot safely reevaluate just part of a window. This includes order-sensitive windows with tied keys in the required rows, unbounded global frames that depend on rows outside those affected by the change, and finite frames that exceed the key or neighbor scan limits.
Refresh a global top-K result
Use a top-level ORDER BY with a fixed integer LIMIT, or filter a single global
ROW_NUMBER() with a predicate such as rn <= 10 or rn < 11.
CREATE MATERIALIZED VIEW paimon.default.top_events AS
SELECT id, score FROM scored_events
ORDER BY score DESC NULLS LAST, id
LIMIT 10;
REFRESH MATERIALIZED VIEW paimon.default.top_events;
Incremental refresh uses eligible boolean, integer, date, and decimal order columns. When the result contains the order columns, refresh can look up the previous cutoff in the target snapshot. Otherwise it reads the order columns from the previous source snapshots. Changes strictly after that cutoff leave the top-K rows alone and still advance the source positions.
When a row enters or leaves the result, Spark finds the new cutoff using the
order columns before evaluating the projected values. A deletion can refill a
vacancy from later keys. The refresh compares the new prefix with the rows
actually stored in the target, including the chosen members of a tie. Include
a unique tie breaker in ORDER BY if the query needs a repeatable order for equal
keys.
Refresh top-K groups through a catalog intermediate table
For eligible top-K queries over a single-source GROUP BY, Paimon maintains the grouped
results in a separate Data Evolution table in the same catalog and database. Project the
grouping keys and use supported scalar grouping and order columns.
The following global top-K view keeps the ten event IDs with the highest counts.
CREATE MATERIALIZED VIEW paimon.default.top_event_counts AS
SELECT id, COUNT(*) AS n FROM events
GROUP BY id
ORDER BY n DESC, id
LIMIT 10;
REFRESH MATERIALIZED VIEW paimon.default.top_event_counts;
SELECT * FROM paimon.default.top_event_counts__mv_groups;
A partitioned top-K can also use a catalog intermediate table. Rank the grouped rows with
one ROW_NUMBER() window and use a fixed positive bound on its rank. For an events table
with integer region_id and item_id columns, the following view keeps up to ten items in
each region.
CREATE MATERIALIZED VIEW paimon.default.top_items_by_region AS
WITH item_counts AS (
SELECT region_id, item_id, COUNT(*) AS n FROM events GROUP BY region_id, item_id
), ranked AS (
SELECT region_id, item_id, n,
ROW_NUMBER() OVER (PARTITION BY region_id ORDER BY n DESC, item_id) AS rn
FROM item_counts
)
SELECT region_id, item_id, n FROM ranked WHERE rn <= 10;
REFRESH MATERIALIZED VIEW paimon.default.top_items_by_region;
Every refresh first maintains the grouped rows, then evaluates top-K changes from the intermediate table's committed snapshots. For eligible partitioned rankings, the second refresh replays the ranking partitions touched by changed grouped rows. A change outside a global cutoff can advance the final view's position without rewriting its rows. If the final refresh fails after the grouped results commit, the next refresh resumes from the positions committed by each table.
Paimon creates the intermediate table when it creates an eligible view on the main branch.
Creation and refresh use the view name followed by __mv_groups. Both tables use the
catalog's normal storage locations and permissions.
Merge partitioned top-K candidates
An ordered limit can refresh from a separate table of partitioned top-K candidates. For example, keep the three best scores from each shard and use those candidates for the global top three.
CREATE MATERIALIZED VIEW paimon.default.top_scores AS
WITH ranked AS (
SELECT id, shard, score,
ROW_NUMBER() OVER (PARTITION BY shard ORDER BY score DESC, id) AS rn
FROM scored_events
)
SELECT id, score FROM ranked WHERE rn <= 3
ORDER BY score DESC, id LIMIT 3;
Use the same total order for both rankings and retain at least the global limit in
each shard when the result must equal the global top-K over all source rows.
top_scores__mv_candidates stores the rows selected by the partitioned ranks.
Refresh reevaluates affected ranking partitions before applying the global limit
to the committed candidate snapshots. Deleting a winner can promote another row
from its shard into the candidate table. An eligible join or aggregate can also
consume bounded partitioned ranks from the candidate table.
Aggregate the latest records in a CDC history
On the main branch, an eligible grouped aggregate over the latest rows of a single
Data Evolution history can use a catalog intermediate table. Use ROW_NUMBER() over
each business key, order by version and a unique tie breaker, and retain rank one.
Put the deletion marker filter on the ranked rows so a tombstone removes the key
from the latest result.
CREATE MATERIALIZED VIEW paimon.default.orders_by_status AS
WITH ranked AS (
SELECT order_id, status, deleted,
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY revision DESC, event_id DESC) AS rn
FROM order_changes
)
SELECT status, COUNT(*) AS orders
FROM ranked WHERE rn = 1 AND NOT deleted
GROUP BY status;
REFRESH MATERIALIZED VIEW paimon.default.orders_by_status;
Refresh first updates the latest rows for affected keys in
orders_by_status__mv_latest, an ordinary Data Evolution table in the same catalog and
database. The aggregate then consumes the intermediate table's committed snapshots.
An older version can advance the source position without changing the selected row.
Physically deleting the selected source record allows the preceding record to become
the latest if it still exists.
Eligible equality joins can also use the selected latest rows as an intermediate input. When only the other side of the join changes, refresh can read the committed latest rows and the new snapshot from that side. If a source schema change requires a planned recompute of an intermediate with supported scalar columns, refresh compares the results with the previous intermediate snapshot and can preserve the row IDs of unchanged rows.
Aggregate a Data Evolution table
Compound groups
Spark can group by several scalar columns and can group the result of a supported
composition such as a join, set operation, predicate subquery, or CTE. Use
GROUPING SETS, ROLLUP, or CUBE to combine levels of grouping. The following
view counts events by ID and by enabled status.
CREATE MATERIALIZED VIEW paimon.default.event_counts AS
SELECT enabled, id, grouping_id(enabled, id) AS level, count(*) AS event_count
FROM events
GROUP BY GROUPING SETS ((enabled, id), (enabled));
For COUNT, COUNT(DISTINCT ...), and eligible MIN, MAX, SUM, and AVG
inputs, refresh can recompute the affected groups at the previous and current
snapshots. Spark uses the full grouping key, including the grouping level for
grouped subtotals. The SELECT can omit grouping columns. Refresh can
prune grouping sets whose constant keys cannot match the changed keys and use the
remaining grouping sets to prune source files.
For an eligible grouped projection with the group keys and an unfiltered row
count, refresh can apply signed count changes and sums of TINYINT, SMALLINT,
or INT values to the values stored in the target snapshot. SUM needs a
matching count of non-NULL input values. AVG can reuse a matching sum and
count. The aggregate arguments and their FILTER conditions must match.
For an eligible single-source append, refresh can merge projected counts,
integer sums, and extrema with the stored values. These paths can skip
unchanged source files within an affected group.
When a small set of source changes leaves the row counts, non-NULL counts,
and contributing sums unchanged, refresh can skip eligible groups even if the
query hides their keys or uses HAVING. This can also skip a grand total during
a group-key move. For a complete grouping-set result that projects COUNT(*)
and compatible integer measures, refresh can derive a hidden grand total from
the target values. Each input row contributes once to each grouping set.
An eligible average needs a matching non-NULL count. The refresh updates the total
and replays affected detail groups in one commit.
Refresh uses the original pinned query when Spark's numerical result cannot be replayed exactly. Floating-point inputs and potentially overflowing sums are examples.
Simple groups
Use GROUP BY with one physical column of an integral, boolean, date, decimal, or
STRING type with binary collation. Supported aggregate functions are COUNT, SUM, AVG,
MIN, MAX, and COUNT(DISTINCT ...). The query can use WHERE, HAVING, and
aggregate FILTER clauses. It can also omit the grouping key from the SELECT list.
CREATE MATERIALIZED VIEW paimon.default.event_counts AS
SELECT enabled, COUNT(*) AS events, COUNT(DISTINCT id) AS event_ids
FROM events
GROUP BY enabled;
REFRESH MATERIALIZED VIEW paimon.default.event_counts;
Paimon reads affected grouping keys from changed row-ID ranges in the previous and current source snapshots. Spark evaluates the aggregates over the complete groups for those keys, including all rows that share a NULL key. Eligible key and WHERE predicates prune unrelated source files. Paimon applies the change in multiplicity of each projected row and commits it with the source position in the same target snapshot.
Refresh can rebuild the view when the required history is unavailable, the read schema changes,
or the affected keys or projected changes exceed the incremental budget. It also rebuilds when
the previous aggregate values cannot be reproduced exactly. Examples include floating-point
SUM and AVG, and sums whose accumulator can overflow given the source size and value type.
Count distinct members through a catalog intermediate table
On the main branch, eligible single-source GROUP BY queries that select every grouping key
and one unfiltered COUNT(DISTINCT column) use a separate Data Evolution table in the same
catalog and database. Its name is the view name followed by __mv_groups. The table stores one
row per group and member, with the number of source rows for that member.
For an events table with integer week_id, channel, and user_id columns, the following
view counts distinct active users per week and channel.
CREATE MATERIALIZED VIEW paimon.default.weekly_active_users AS
SELECT week_id, channel, COUNT(DISTINCT user_id) AS active_users
FROM events GROUP BY week_id, channel;
REFRESH MATERIALIZED VIEW paimon.default.weekly_active_users;
Refresh first updates member counts from the source snapshots. The view then consumes the intermediate table's committed snapshots. Adding a copy of an existing member or deleting a copy that still has survivors preserves the distinct count. A NULL member keeps a group with only NULL input rows in the result with a count of zero.
Reuse grouped results in a further aggregate or window
An eligible aggregate or window can consume a single-source grouped result from
<view>__mv_groups. For example, maintain a visit count per member, then count the
members who meet a threshold.
CREATE MATERIALIZED VIEW paimon.default.active_members AS
WITH visits AS (
SELECT region_id, member_id, COUNT(*) AS n
FROM events GROUP BY region_id, member_id
)
SELECT region_id, COUNT(*) AS active
FROM visits WHERE n >= 3 GROUP BY region_id;
A window over daily groups can use the same boundary to refresh rolling values from changed daily rows. Eligible partitioned windows refresh affected ranking or aggregation partitions. Supported finite global frames can use the existing neighbor scan on the intermediate table.
Grouping sets, rollups, and eligible pivots can also reuse preaggregated rows. This allows a final report to summarize qualifying members across several levels or present those counts as columns.
An eligible window followed by a filter on its output can store the qualifying rows
in <view>__mv_window. For example, use LAG to compare each measurement with its
predecessor, retain large changes, and count the resulting alerts. An update can add
or retract an alert from a neighboring row before the downstream aggregate refreshes.
Summarize preaggregated facts through an equijoin
On the main branch, an eligible grouped query can materialize an explicit single-source
preaggregation before an equijoin. For example, summarize the amount by customer
and week before calculating revenue by each customer's current segment. Use an exact
numeric type, such as DECIMAL(10, 2), for the amount.
CREATE MATERIALIZED VIEW paimon.default.revenue_by_segment AS
WITH customer_totals AS (
SELECT week_id, customer_id, SUM(amount) AS total
FROM orders GROUP BY week_id, customer_id
)
SELECT c.segment, SUM(t.total) AS revenue
FROM customer_totals t JOIN customers c ON t.customer_id = c.customer_id
GROUP BY c.segment;
REFRESH MATERIALIZED VIEW paimon.default.revenue_by_segment;
The ordinary Data Evolution table revenue_by_segment__mv_groups stores the
customer-week totals in the same catalog and database. Refresh maintains those totals
from the order snapshots, then consumes the committed intermediate and customer
snapshots for the join and final aggregate. When a customer's segment changes, the
stored totals can be joined with the new segment without reading the order details.
An equality semi or anti join can consume a grouped result filtered by a threshold. For example, join a list of customers to grouped event counts filtered to customers with at least three qualifying events.
Consume an ordered prefix
An eligible equality join, aggregate, window, or second ranking can consume a
single-source ORDER BY with a fixed positive LIMIT or a bounded global
ROW_NUMBER(). Paimon keeps the prefix in <view>__mv_topk and refreshes the
downstream result from its committed snapshots. For example, select the highest
scoring events before attaching category labels.
CREATE MATERIALIZED VIEW paimon.default.scored_event_labels AS
WITH leaders AS (
SELECT id, category_id, score FROM scored_events ORDER BY score DESC, id LIMIT 10
)
SELECT leaders.id, leaders.score, categories.label
FROM leaders JOIN categories ON leaders.category_id = categories.id;
Pivot grouped results
CREATE MATERIALIZED VIEW paimon.default.event_status_totals AS
SELECT id, active_count, inactive_count
FROM (SELECT id, enabled FROM events)
PIVOT (COUNT(*) FOR enabled IN (true AS active_count, false AS inactive_count));
REFRESH MATERIALIZED VIEW paimon.default.event_status_totals;
An eligible grouped PIVOT refreshes the groups affected by source changes.
Rows whose pivot value is outside the listed cells still contribute to group
existence. A pivot without grouping columns uses the original pinned query.
Scalar aggregates
A scalar aggregate operates on all qualifying rows of a Data Evolution input or
a supported compound query. Use COUNT, COUNT(DISTINCT ...), SUM, AVG, MIN, or
MAX. A query can combine these aggregates and use WHERE, HAVING, and aggregate
FILTER clauses.
CREATE MATERIALIZED VIEW paimon.default.event_totals AS
SELECT COUNT(*) AS events, COUNT(id) AS id_count, SUM(id) AS id_sum, AVG(id) AS average_id
FROM events
WHERE enabled;
REFRESH MATERIALIZED VIEW paimon.default.event_totals;
Refresh can apply changes to projected counts and exact sums of TINYINT,
SMALLINT, or INT values using the previous target snapshot. An eligible
AVG uses a matching non-NULL count and a sum that is projected or can be
recovered exactly. For supported fixed-width extrema, Spark searches unchanged
rows when a deleted or updated value may remove the previous extreme.
COUNT(DISTINCT ...) checks for surviving copies of each affected non-NULL tuple.
An eligible COUNT(*) over an inner equijoin multiplies per-key row counts so the
refresh can avoid enumerating matching pairs.
When numerical bounds, SQL evaluation, or missing projected aggregate values require complete evaluation, Spark runs the original query at the pinned source snapshots. Schema changes and missing history can also trigger a rebuild. Paimon commits the result and all source positions together. If a check proves that the scalar result is unchanged, refresh advances only the source positions.