Incremental refresh for materialized views

Incremental refresh on a materialized view detects changes in the source data and recomputes only the affected results, rather than recomputing the entire query. The following sections cover the semantics, requirements, supported SQL operations, query and upstream write design, diagnosing full recomputes, and refresh policies.

For an overview of how pipelines refresh, see How do pipelines refresh?. Because incremental refresh requires serverless compute, see also Serverless vs. classic compute for pipelines.

When running updates on materialized views using serverless pipelines, many queries can be incrementally refreshed. Incremental refreshes save compute costs by detecting changes in the data sources used to define the materialized view and incrementally computing the result.

Refreshes run on serverless compute

Refresh operations are run on serverless pipelines, regardless if the operation was defined as standalone or with Lakeflow pipelines.

For standalone materialized views, your workspace does not need to be enabled for serverless Lakeflow pipelines. The refresh uses a serverless pipeline automatically.

For materialized views defined using Lakeflow pipelines, you must configure the pipeline to use serverless. See Configure a serverless pipeline.

What are the refresh semantics for materialized views?

Materialized views guarantee equivalent results to batch queries. For example, consider the following aggregate query:

SELECT account_id,
  COUNT(txn_id) txn_count,
  SUM(txn_amount) account_revenue
FROM transactions_table
GROUP BY account_id

When you run this query using any Azure Databricks product, the result is computed using batch semantics to aggregate all records in the source transactions_table, meaning that all source data is scanned and aggregated in one operation.

Note

Some Azure Databricks products cache results automatically within or across sessions if data sources have not changed after the last query has run. Automatic caching behaviors differ from materialized views.

The following example turns this batch query into a materialized view:

SQL

CREATE OR REPLACE MATERIALIZED VIEW transaction_summary AS
SELECT account_id,
  COUNT(txn_id) txn_count,
  SUM(txn_amount) account_revenue
FROM transactions_table
GROUP BY account_id

Python

@dp.materialized_view()
def transaction_summary():
  return (spark.read.table("transactions_table")
    .groupBy("account_id")
    .agg(
      count("*").alias("txn_count"),
      sum("txn_amount").alias("account_revenue")
    )
  )

When you refresh a materialized view, the computed result is identical to the batch query semantics. This query is an example of a materialized view that can be incrementally refreshed, meaning that the refresh operation makes a best-effort attempt to only process new or changed data in the source transactions_table to compute the results.

Data source considerations for materialized views

While you can define a materialized view against any data source, not all data sources are well-suited to materialized views. Consider the following caveats and recommendations:

Important

Materialized views make a best-effort attempt to incrementally refresh results for supported operations. Some changes in data sources require a full refresh. You can define a refresh policy that fails rather than run a full refresh.

All data sources for materialized views should be robust to full refresh semantics, even if the query that defines the materialized view supports incremental refresh.

  • For queries where a full refresh would be cost-prohibitive, use streaming tables to guarantee exactly-once processing. Examples include very large tables.
  • Do not define a materialized view against a data source if records should only be processed once. Instead, use streaming tables. Examples include the following:
    • Data sources that don't retain data history, such as Kafka.
    • Ingest operations, such as queries that use Auto Loader to ingest data from cloud object storage.
    • Any data source where you plan to delete or archive data after processing but need to retain information in downstream tables. For example, a date-partitioned table where you plan to delete records older than a certain threshold.
  • Not all data sources support incremental refreshes. The following data sources support incremental refresh:
    • Delta tables, including Unity Catalog managed tables and external tables backed by Delta Lake.
    • Materialized views.
    • Streaming tables, including the targets of AUTO CDC ... INTO operations.
    • Unity Catalog managed Iceberg tables (v2 and v3). Iceberg v3 is recommended for best incremental refresh support. See Use Apache Iceberg v3 features.
  • Materialized views can read foreign Iceberg tables, but incremental refresh isn't supported for these sources.
  • Some incremental refresh operations require row-tracking to be enabled on the queried data sources. Row-tracking is a Delta Lake feature only supported by Delta tables, which include materialized views, streaming tables, and Unity Catalog managed tables. See Row tracking in Azure Databricks.

Optimize materialized views

To get the best performance, Databricks recommends enabling the following features on all materialized view source tables:

You can set these features during creation, or later with the ALTER TABLE statement (run from Databricks SQL). For example:

ALTER TABLE <table-name> SET TBLPROPERTIES (
  delta.enableRowTracking = true,
  delta.enableDeletionVectors = true);

You don't need to turn on legacy change data feed (delta.enableChangeDataFeed) on source tables. If a source table already uses legacy change data feed, see Migrate from legacy change data feed.

If your source tables have primary key, foreign key, or unique constraints, consider declaring them as informational constraints with the RELY option. Azure Databricks doesn't enforce these constraints, but the query optimizer can use them to generate more efficient plans for the query behind your materialized view, such as eliminating unnecessary joins and aggregations. See Optimize queries with RELY on primary key and unique constraints.

How upstream writes affect incremental refresh

An incremental refresh processes the changeset: the rows in each source table that changed since the last refresh. The smaller the changeset relative to the materialized view, the more likely incremental refresh is cheaper than a full recompute. How you write to source tables has a large effect on changeset size.

Azure Databricks models every change to a source row as a delete of the old row followed by an insert of the new row. An update to one column of one row produces one delete and one insert in the changeset. With row tracking enabled, Azure Databricks uses row IDs to identify which rows changed.

The write pattern you use on a source table determines how many rows look changed:

  • MERGE and UPDATE keep row IDs: A row keeps the same row ID when it is modified with MERGE or UPDATE, and rows that the statement doesn't touch are not part of the changeset. Prefer MERGE on a stable key when most incoming rows are unchanged.
  • Overwrites rewrite rows: INSERT OVERWRITE, the Delta replaceWhere write option, and dynamic partition overwrite replace every row in the affected partitions or table, even if the values are identical. The rewritten rows get new row IDs, so they all appear in the changeset. For example, a daily job that rewrites the last 30 days of a table makes all 30 days look changed, even if only one day has new data.
  • CREATE OR REPLACE TABLE replaces the table: The source gets a new table identity, so the next refresh of every downstream materialized view is a full recompute, reported as QUERY_FINGERPRINT_CHANGED, however few rows changed. Use MERGE instead, or INSERT OVERWRITE when you must replace all rows.

To keep changesets small when you control the upstream writes:

  • Use MERGE keyed on a stable primary key instead of overwriting partitions. An overwrite also removes rows that are missing from the new data, and a MERGE with only WHEN MATCHED and WHEN NOT MATCHED clauses does not. If the replaced data can drop rows, add a WHEN NOT MATCHED BY SOURCE ... THEN DELETE clause restricted to the same partitions or window.
  • Add a condition to the WHEN MATCHED clause so that rows are only updated when their values change. For example, compare a hash of the non-key columns: WHEN MATCHED AND NOT (t.row_hash <=> s.row_hash) THEN UPDATE SET *. The null-safe comparison (<=>) makes sure that a change between a null and a non-null hash also triggers the update. Without the condition, MERGE rewrites every matched row even if nothing changed. In dbt, this corresponds to the merge incremental strategy with a matched condition.
    • Compute row_hash so that it is never null and keeps column identity, for example sha2(to_json(struct(<non-key columns>)), 256). Hashes built with concat are null when any column is null, and concat_ws, hash, and xxhash64 skip null values, so different rows can produce the same hash. Alternatively, skip the hash and compare the columns null-safely, for example WHEN MATCHED AND NOT (t.amount <=> s.amount AND t.status <=> s.status) THEN UPDATE SET *.
  • If you must reprocess a look-back window in a pipeline, consider a REPLACE WHERE flow for that step instead of a materialized view over an overwritten table.
  • Enable deletion vectors so that row-level changes rewrite fewer rows, which keeps the changeset small.
  • If refreshes fall back to a full recompute with the TOO_MANY_FILE_ACTIONS reason, refresh more often or write fewer, larger files. The limit counts every data-changing file action on the source table, including writes that the materialized view's filters exclude.

Refresh types for materialized views

When a materialized view is updated, you can specify a refresh or a full refresh.

  • A refresh attempts to do an incremental refresh, but will do a full recompute of the data if needed. Incremental refresh is only available when the compute you are connected to is serverless.
  • A full refresh always recalculates all inputs to the materialized view, and resets all checkpoints.

To determine which refresh type an update used, see Determine the refresh type of an update.

Default refresh

The default refresh for a materialized view on serverless attempts to perform an incremental refresh. An incremental refresh processes changes in the underlying data after the last refresh and then appends that data to the table. Depending on the base tables and included operations, only certain types of materialized views can be incrementally refreshed. If an incremental refresh is not possible or the connected compute is classic instead of serverless, a full recompute is performed.

Note

Azure Databricks applies a full or incremental refresh. The decision is based on which option is more cost-effective, and whether a query supports incremental refresh. To change this behavior, see Refresh policy.

The output of an incremental refresh and a full recompute are the same. Azure Databricks runs a cost analysis to choose the cheaper option between an incremental refresh and a full recompute.

Only materialized views updated using serverless pipelines can use incremental refresh. Materialized views that do not use serverless pipelines are always fully recomputed.

When you create materialized views with a SQL warehouse or serverless Lakeflow pipelines, Azure Databricks incrementally refreshes them if their queries are supported. If a query uses unsupported expressions, Azure Databricks runs a full recompute instead, which can increase costs.

To determine which refresh type an update used, see Determine the refresh type of an update.

Full refresh

A full refresh overwrites the results in the materialized view by clearing the table and checkpoints, and reprocessing all data available in the source.

To perform a full refresh on materialized views defined using Databricks SQL, use the following syntax:

REFRESH MATERIALIZED VIEW mv_name FULL

For materialized views defined in Lakeflow pipelines, you can choose to run a full refresh on selected datasets or on all datasets in a pipeline. See Pipeline refresh semantics.

Important

When a full refresh runs against a data source where records have been removed due to data retention threshold or manual deletion, removed records are not reflected in computed results. You may be unable to recover old data if the data is no longer available in the source. This might also change the schema for columns that no longer exist in the source data.

Support for materialized view incremental refresh

The following table lists support for incremental refresh by SQL keyword or clause. To test a specific query for incrementalizability, you can use EXPLAIN CREATE MATERIALIZED VIEW.

Important

Some keywords and clauses require row-tracking to be enabled on the queried data sources. See Row tracking in Azure Databricks.

These keywords and clauses are marked with a star (*) in the following table.

SQL keyword or clause PySpark dataframe equivalent Support for incremental refresh
SELECT expressions* df.select() or df.selectExpr() Yes, expressions including deterministic built-in functions and immutable user-defined functions (UDFs) are supported.
GROUP BY df.groupBy().agg() Yes
WITH Chaining dataframe variables. Yes, common table expressions are supported.
WITH RECURSIVE N/A No. Materialized views that use recursive CTEs are not eligible for incremental refresh and fall back to a full recompute.
UNION ALL* df.union or df.unionAll Yes
FROM df = spark.read... Supported base tables include Delta tables, Unity Catalog managed Iceberg tables, materialized views, and streaming tables.
WHERE, HAVING* df.filter(), df.where(), df.groupBy().filter() Filter clauses such as WHERE and HAVING are supported.
INNER JOIN* df.join() Yes
LEFT OUTER JOIN* df.join(... how="left") Yes
FULL OUTER JOIN* df.join(... how="full") Yes
RIGHT OUTER JOIN* df.join(... how="right") Yes
LEFT SEMI JOIN, LEFT ANTI JOIN, and EXISTS, NOT EXISTS, IN, or NOT IN subqueries df.join(... how="left_semi"), df.join(... how="left_anti") Yes. Left anti joins, including NOT EXISTS and NOT IN subqueries that the optimizer rewrites into them, are supported. Left semi joins are supported when the join condition uses only equality comparisons. This includes EXISTS and IN subqueries that the optimizer rewrites as left semi joins. A left semi join with a non-equality condition forces a full recompute.
OVER df.over(window.partitionBy) functions Yes. PARTITION_BY columns must be specified for incrementalization on window functions.
QUALIFY df.over(w).filter(...) Yes
EXPECTATIONS @dp.expect Yes, materialized views that include expectations can be incrementally refreshed. However, incremental refresh is not supported for the following cases:
  • When the materialized view reads from a view that contains expectations.
  • When the materialized view has a DROP expectation and includes NOT NULL columns in its schema.
UDFs UDFs Azure Databricks attempts to detect when a UDF changes behavior and perform a full refresh. However, UDFs that call other functions or libraries may change behavior in ways that Azure Databricks does not recognize. When the behavior of a UDF changes, it is your responsibility to perform a full refresh to apply the updated UDF to the full materialized view.
Non-deterministic functions Non-deterministic functions Time functions such as current_date(), current_timestamp(), and now() are supported in a WHERE condition that can be applied directly to one input table. The view can still join that input to other tables. The same functions in a SELECT list, join condition, or aggregate force a full recompute. Other non-deterministic functions are not supported. See Rolling windows with current_date().
Non-deterministic data types Non-deterministic data types Aggregations that sum floating-point values, such as SUM, AVG, and covariance, can produce non-deterministic results over FLOAT or DOUBLE columns and force a full refresh. Cast these columns to DECIMAL in the expression (for example, SUM(CAST(revenue AS DECIMAL(18,2)))) to allow incremental refresh.
Unsupported sources Unsupported sources Sources such as volumes, external locations, and foreign catalogs are not supported. Foreign Iceberg tables are supported as sources, but not for incremental refresh. Unity Catalog managed Iceberg tables are supported.

Design queries for incremental refresh

A query can use only supported operators and still be expensive to maintain incrementally. The following guidelines help both eligibility and the cost model's choice. Start with a straightforward query, check how it refreshes (see Determine the refresh type of an update), and rewrite only when the results show a problem.

Prefer aggregates at the top of the query

Where you can, put GROUP BY aggregation in the outermost query block. A query that joins or aggregates the results of a GROUP BY can still refresh incrementally, but it can be more expensive to maintain. The cost model can reject deeply nested shapes with EXCESSIVE_OPERATOR_NESTING. Simple projections and HAVING filters on top of an aggregate are supported, but HAVING uses a slower aggregation technique.

The following queries compare the two shapes:

-- Harder to maintain: joins on top of an aggregate
SELECT c.segment, a.total
FROM (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) a
JOIN customers c ON a.customer_id = c.customer_id;

-- Easier to maintain: join first, aggregate last.
-- Returns the same totals, plus customer_id, when customer_id is unique in customers.
SELECT c.segment, o.customer_id, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.segment, o.customer_id;

Split complex logic into layered materialized views

A single materialized view with many joins, nested subqueries, or several levels of aggregation is harder to maintain incrementally. The cost model can reject it with reasons such as NUM_JOINS_THRESHOLD_EXCEEDED or EXCESSIVE_OPERATOR_NESTING. Azure Databricks doesn't publish a fixed join limit, because the threshold depends on the query and the data.

When a materialized view is consistently fully recomputed for these reasons, split it into a chain of simpler materialized views. For example, build one materialized view that joins facts to dimensions, and a second materialized view that aggregates the joined result. Each layer refreshes on its own, and a change to one source only flows through the layers that depend on it.

Join on keys

  • Use equality joins (ON a.key = b.key) on stable, well-distributed keys. Joins on columns that change frequently produce larger changesets on both sides.
  • Treat range joins and other non-equi joins (BETWEEN, <, >) as a risk for incremental performance. A change on one side can match many rows on the other side. Where the semantics allow it, convert the range join to an equi-join. For example, expand a date-range dimension into one row per date and join on the date. Otherwise, isolate the range join in its own materialized view so that the rest of the pipeline can refresh incrementally.
  • If the join keys are primary or foreign keys, declare them as informational constraints with RELY. See Optimize materialized views.

Filters and predicate pushdown

Incremental refresh uses the Spark optimizer to push filters down to the source tables. Where possible, filters are also pushed down to the changeset, so that changes outside the filter aren't processed. Changeset filtering uses the filters that apply directly to each source's own columns, including filters that the optimizer pushes through a join. It doesn't infer filters from join conditions, so a filter on one side of a join doesn't prune the other side's changeset.

Pushdown isn't required for correctness, but it affects cost. When the filter is simple, write it explicitly on each source so that each source's changeset is pruned. The following queries return the same rows, but only the second one prunes the line_items changeset:

-- The line_items changeset isn't filtered
SELECT o.order_id, l.sku, l.qty
FROM orders o
JOIN line_items l ON o.order_id = l.order_id AND o.order_date = l.order_date
WHERE o.order_date >= '2025-01-01';

-- Explicit filter on both sources
SELECT o.order_id, l.sku, l.qty
FROM orders o
JOIN line_items l ON o.order_id = l.order_id AND o.order_date = l.order_date
WHERE o.order_date >= '2025-01-01'
  AND l.order_date >= '2025-01-01';

For an outer join, filter the outer-joined source in the ON clause or in a subquery, for example LEFT JOIN line_items l ON o.order_id = l.order_id AND o.order_date = l.order_date AND l.order_date >= '2025-01-01'. A WHERE predicate on that source removes unmatched rows and changes the results.

To confirm that filters are pushed down, check the query profile for the refresh.

Rolling windows with current_date()

For workloads that recompute a moving window of recent data, such as reprocessing the last 7 days on each update to pick up late-arriving records, Azure Databricks recommends a REPLACE WHERE flow instead of a materialized view that filters on current_date(). A REPLACE WHERE flow deletes and recomputes only the rows that match its predicate, and it supports incremental refresh with predicates such as date >= date_add(current_date(), -7):

CREATE STREAMING TABLE daily_customer_revenue
FLOW REPLACE WHERE order_date >= date_add(current_date(), -7) BY NAME
SELECT customer_id, order_date, SUM(amount) AS revenue, COUNT(*) AS orders
FROM orders
GROUP BY customer_id, order_date;

Rows older than the window stay in the target table during regular updates, so the table keeps history even if the source deletes old data. A full refresh recomputes only the current window and permanently deletes older rows. If the source doesn't keep that history, set the table property pipelines.reset.allowed to false.

To report on only the last N days, filter on the date when you query the table, or in a view on top of it. To keep the flow eligible for incremental refresh, use a moving lower bound, and include the predicate column in GROUP BY and join keys. See Incremental refresh.

If you use a materialized view instead, time functions such as current_date() are supported for incremental refresh only in a WHERE condition that can be applied directly to one input table. The view can still join that input to other tables. Using them anywhere else, for example datediff(current_date(), order_date) AS age_days in the SELECT list, makes the query non-deterministic and forces a full recompute on every refresh. Compute values that depend on the current date in the query that reads the materialized view, or in a view on top of it.

Shared multi-tenant source tables

When many tenants share a source table and each materialized view reads one tenant, filter on the tenant column in the materialized view definition, and write the filter explicitly on each source that has the column. For an outer-joined source, put the filter in the ON clause (see Filters and predicate pushdown). Filters push down to the changeset where possible, so changes for other tenants can be skipped.

How much work is skipped depends on the physical layout of the source as well as the query. Cluster the source table on the tenant column, for example with liquid clustering, so that each tenant's rows are in separate files. Writers that touch many tenants in one operation, or overwrites that rewrite files shared by several tenants, can still enlarge every tenant's changeset. Validate the design with a representative refresh and check the query profile before you rely on it.

Incrementalization insights

When you develop a pipeline in the pipeline editor or monitor a pipeline update, the Tables panel includes an Incrementalization column that shows how each materialized view was processed in the latest update:

Status Description
Incremental The materialized view was incrementally refreshed.
Full recompute The materialized view was fully recomputed.
No change No source data changes were detected, so the materialized view was not updated.

When Azure Databricks detects a problem that prevented a materialized view from incrementally refreshing, or that might prevent it in a future update, and has a recommended fix, a Lightbulb icon. insight appears next to the status. Select it to open the Issues panel filtered to that materialized view. Each insight explains the cause and recommends a fix. Common fixes include:

Insights can appear even when the status is No change or for a dry run, so you can fix issues before they affect an update. An insight can also take you to the relevant line in your source code. From the monitoring UI, this opens the pipeline editor at that line. Insights cover common issues that prevent incremental refresh. The absence of an insight does not guarantee that a materialized view can incrementally refresh.

You can also ask Genie Code why a materialized view is not refreshing incrementally, and it'll explain and fix the issues. See Use Genie Code for pipeline development.

Incrementalization insights also appear in the query profile for a materialized view refresh, for both pipeline and standalone materialized views. The query profile shows why a refresh fell back to a full recompute, including source table settings and unsupported query operators, and lets you select Optimize to open Genie Code in the relevant editor to address the issue. See the FLOW_FULL_RECOMPUTE insight in FLOW_FULL_RECOMPUTE.

To get the same information programmatically, or to review earlier updates, query the event log as described in the following section.

Determine the refresh type of an update

To optimize the performance of materialized view refreshes, Azure Databricks uses a cost model to select the technique used for the refresh. The following table describes these techniques:

Technique Incremental refresh? Description
FULL_RECOMPUTE No The materialized view was fully recomputed
NO_OP Not applicable The materialized view was not updated because no changes to the base table were detected.
Any of:
  • ROW_BASED
  • PARTITION_OVERWRITE
  • WINDOW_FUNCTION
  • APPEND_ONLY
  • GROUP_AGGREGATE
  • GENERIC_AGGREGATE
Yes The materialized view was incrementally refreshed using the specified technique.

See also Refresh policy.

To determine the technique used, query the Lakeflow pipeline event log where the event_type is planning_information:

SELECT
  timestamp,
  message
FROM
  event_log(TABLE(<fully-qualified-table-name>))
WHERE
  event_type = 'planning_information'
ORDER BY
  timestamp desc;

Replace <fully-qualified-table-name> with the fully qualified name of the materialized view, including the catalog and schema.

Sample output for this command:

timestamp message
2025-03-21T22:23:16.497+00:00 Flow 'sales' has been planned to be executed as ROW_BASED.

See Pipeline event log.

Eligible versus chosen technique

Two separate decisions determine how a materialized view refreshes:

  1. Eligibility: Whether the query structure supports incremental refresh at all. EXPLAIN CREATE MATERIALIZED VIEW reports eligibility before you create the materialized view, and lists the operators or settings that prevent it.
  2. Choice: On each refresh, the cost model compares the eligible incremental techniques with a full recompute for the current changeset and picks the cheapest. An eligible materialized view can still be fully recomputed, for example when a large fraction of a source table changed.

EXPLAIN answers only the first question. To see what was chosen and why, read the planning_information event for the update. Each event lists every technique that was considered, with these fields:

  • is_applicable: Whether the technique could be used for this refresh.
  • is_chosen: Whether the technique was used.
  • incrementalization_issues: The reasons a technique couldn't be used or was rejected, including cost_model_rejection_subtype when the cost model rejected an incremental plan.

For a ready-to-use query that returns the chosen technique and the issues for each flow, see the incremental refresh debugging example in Pipeline event log. For the full list of issue types, see Pipeline event log schema.

Cost-model rejections and fixes

When the chosen technique is FULL_RECOMPUTE on an eligible materialized view, the planning_information event contains a technique_information entry without a maintenance_type. Its incrementalization_issues include INCREMENTAL_PLAN_REJECTED_BY_COST_MODEL with one or more of the following cost_model_rejection_subtype values. The rejected incremental technique itself still shows is_applicable as true and has no issues. Azure Databricks doesn't publish fixed values for these thresholds, because they depend on the query, the data, and the compute.

Reason What it means What to try
CHANGESET_SIZE_THRESHOLD_EXCEEDED Too many source rows changed since the last refresh for incremental processing to be cheaper, or earlier incremental refreshes with similar changes ran slower than a full recompute. Reduce rewrites in upstream writes (see How upstream writes affect incremental refresh). Refresh more often so that each changeset is smaller. If most of the data legitimately changes each time, or upstream writes are already small, a full recompute is likely the cheaper choice for this query.
TABLE_SIZE_THRESHOLD_EXCEEDED The size of the source tables makes the incremental plan more expensive than a full recompute. Refresh more often so that each refresh processes fewer changes. Push filters down to the sources (see Design queries for incremental refresh), or split the materialized view so that the expensive part reads less data.
SCAN_SELECTIVITY_THRESHOLD_EXCEEDED A time-based filter can require scanning too much of a source table. This reason can also appear when scan size statistics are unavailable. Refresh more often so that each changeset is smaller. If the filter reads a large share of the table, cluster or partition the table on the filtered column so that the scan can skip files.
NUM_JOINS_THRESHOLD_EXCEEDED The query has too many joins to maintain incrementally at a reasonable cost. Split the joins across layered materialized views. See Design queries for incremental refresh.
EXCESSIVE_OPERATOR_NESTING The query has many levels of nested operators, which makes incremental maintenance risky. Flatten the query, move aggregation to the top, or split it into layered materialized views.
COST_MODEL_REJECTION_SUB_TYPE_UNSPECIFIED The cost model rejected the incremental plan for another reason. Check the query profile and the other incrementalization_issues in the planning_information event.

Other issue types, such as ROW_TRACKING_NOT_ENABLED or PLAN_NOT_INCREMENTALIZABLE, mean that the materialized view wasn't eligible for that refresh. Fix these by changing the source table settings or the query. See Incrementalization insights and Pipeline event log schema.

A cost-model rejection is a decision, not an error. Before you override it, confirm with measurements that incremental refresh is actually cheaper for your workload. See Example: Tune a materialized view and decide when not to force incremental refresh.

Refresh policy

By default, Azure Databricks automatically selects the most cost-effective refresh strategy (incremental or full) based on query structure, data change volume, and system cost modeling. This default behavior optimizes refresh performance without requiring manual configuration.

Some workloads, however, require more predictable or explicitly controlled refresh behavior. To support these scenarios, you can specify a REFRESH POLICY in the materialized view definition. A refresh policy controls whether Azure Databricks performs incremental refresh, when it may fall back to a full refresh, and whether a refresh should fail instead of performing a full recompute.

Using REFRESH POLICY, you can configure the system to:

  • AUTO (default) - Use automatic, cost-based selection. Databricks chooses incremental or full refresh based on efficiency and query capabilities. Recommended for most users.
  • INCREMENTAL - Prefer incremental refresh. Databricks performs incremental refresh whenever possible, even when the cost model estimates that a full refresh is cheaper. It falls back to a full refresh when incremental refresh is temporarily unavailable for an update. If the query isn't eligible for incremental refresh, the refresh or create operation fails.
  • INCREMENTAL STRICT - Strictly require incremental refresh. Incremental refresh is required during normal operation. If incrementalization is not possible, the refresh or create operation fails.
  • FULL - Always perform full refreshes. Databricks never performs incremental refresh, even when the query is incrementalizable.

SQL

-- Create a materialized view with an incremental refresh policy
CREATE MATERIALIZED VIEW IF NOT EXISTS my_mv
REFRESH POLICY INCREMENTAL
AS SELECT a, sum(b) AS sum_b FROM my_catalog.example.my_table GROUP BY a;

Python

from pyspark import pipelines as dp

@dp.materialized_view(
  refresh_policy = 'incremental_strict'
)
def my_mv():
  return spark.read.table("main.default.source_table")

Azure Databricks recommends AUTO for most workloads. The goal of a refresh is the lowest total cost, not incremental processing for its own sake, and an incremental refresh over a large changeset can cost more than a full recompute. Choose a different policy only when you have a specific reason, such as a latency target that unexpected full recomputes would miss.

Important

Under AUTO, and under INCREMENTAL when incremental refresh is temporarily unavailable for an update, falling back to a full recompute doesn't fail the update or raise an error. The only signals are the refresh technique in the event log, the Incrementalization column, and the longer run time. If you depend on incremental refresh, monitor the chosen technique (see Determine the refresh type of an update), or use INCREMENTAL STRICT so that the update fails instead of falling back.

INCREMENTAL overrides cost-model rejections, so Azure Databricks runs an incremental refresh even when it estimates that a full recompute is cheaper. It falls back to a full recompute when incremental refresh is temporarily unavailable for an update, for example after too many file actions on a source. If the query itself isn't eligible (check with EXPLAIN CREATE MATERIALIZED VIEW), the create or refresh fails with MATERIALIZED_VIEW_NOT_INCREMENTALIZABLE. Use it only after you measure that incremental refresh is cheaper for your workload.

The optimal refresh policy depends on your workload characteristics:

  • AUTO is appropriate for most workloads. It balances cost and performance and adapts automatically when query behavior changes.
  • INCREMENTAL is useful when incremental refresh provides benefits, but it is acceptable for Azure Databricks to perform full refreshes when incremental refresh becomes temporarily unavailable for an update, such as after too many file actions on a source table.
  • INCREMENTAL STRICT should be used when incremental refresh is required to meet cost, performance, or SLA constraints, and unexpected full refreshes are unacceptable. This policy is recommended when users prefer the update to fail, allowing them to debug the issue rather than proceed with a full refresh.
  • FULL is suitable when incremental refresh provides little benefit, the dataset is small, or the query structure frequently changes in ways that prevent incrementalization.

For more details, and syntax, see REFRESH POLICY clause (pipelines), or if the dataset is defined in Databricks SQL, REFRESH POLICY clause.

The following features work alongside materialized view incremental refresh:

  • REPLACE WHERE flows: When you need to reprocess a bounded window of data, such as the last seven days to pick up late-arriving records, a REPLACE WHERE flow recomputes and overwrites only the rows that match a predicate. Use it when a materialized view would be fully recomputed because of a look-back rewrite, when the target must keep history that the source has deleted (a full refresh deletes that history unless you set pipelines.reset.allowed to false), or when a dimension change should not recompute all history. See Batch processing with REPLACE WHERE flows.
  • Change data feed from materialized views: You can read the change data feed of a materialized view to replicate its changes downstream or to audit them. See Read a change data feed from a materialized view.
  • streaming tables: For sources that are append-only or must be processed exactly one time, a streaming table processes each record a single time instead of recomputing results from the full source. See Data source considerations for materialized views.

Example: Tune a materialized view and decide when not to force incremental refresh

This example walks through a common case. A daily revenue report joins an orders fact table to a customer dimension that tracks history as a type 2 slowly changing dimension (SCD).

The source tables are:

  • orders: One row per order. A nightly job loads new orders, and late-arriving corrections update existing orders.
  • customers_scd2: One row per customer version, maintained with AUTO CDC ... STORED AS SCD TYPE 2. Each version has __START_AT and __END_AT columns, and the current version has a null __END_AT. See The AUTO CDC APIs: Simplify change data capture with pipelines.

Start with the straightforward query

The following materialized view joins each order to the customer version in effect on the order date and aggregates revenue by date and segment:

CREATE OR REPLACE MATERIALIZED VIEW daily_revenue_by_segment AS
SELECT
  o.order_date,
  c.segment,
  SUM(CAST(o.amount AS DECIMAL(18, 2))) AS revenue,
  COUNT(*) AS order_count
FROM orders o
JOIN customers_scd2 c
  ON o.customer_id = c.customer_id
  AND o.order_date >= c.__START_AT
  AND (o.order_date < c.__END_AT OR c.__END_AT IS NULL)
GROUP BY o.order_date, c.segment;

Before you create it, run EXPLAIN CREATE MATERIALIZED VIEW on the query. Cast amount to DECIMAL so that the floating-point aggregation doesn't force a full recompute (see Support for materialized view incremental refresh). Enable row tracking and deletion vectors on both source tables (see Optimize materialized views).

Check what each refresh does

After a few scheduled refreshes, read the planning_information events (see Eligible versus chosen technique). In this example, refreshes after the nightly load are incremental. Refreshes after a weekly job that rewrites the last 30 days of orders with INSERT OVERWRITE are fully recomputed, with the reason CHANGESET_SIZE_THRESHOLD_EXCEEDED.

Fix the upstream write

The weekly job rewrites 30 days of rows even though only a few of them change. Replace the overwrite with a MERGE that updates only changed rows:

MERGE INTO orders t
USING orders_corrections s
  ON t.order_id = s.order_id
WHEN MATCHED AND NOT (t.row_hash <=> s.row_hash) THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

Now only the corrected orders appear in the changeset, and the refresh after the weekly job is incremental.

This MERGE assumes that orders_corrections contains only new and corrected orders, with the same columns as orders, and that orders are never removed. Unlike the overwrite, it doesn't delete orders that are missing from the source.

If the weekly job must also remove orders, use the complete snapshot of the window as the source and add a deletion restricted to the same window. The delete condition must be exactly the predicate that defines the snapshot, evaluated for the same date. Otherwise, each run deletes orders that the snapshot doesn't cover. For example, compute the window start one time, build the snapshot with WHERE order_date >= window_start, and add WHEN NOT MATCHED BY SOURCE AND t.order_date >= window_start THEN DELETE. Don't add that clause when the source is a corrections-only feed, because it would delete every order in the window that wasn't corrected.

Keep the range join stable

The SCD type 2 join is a range join on __START_AT and __END_AT. Its results are stable over time. When a customer's segment changes, the old version is closed at the change time and a new version starts, so historical orders keep matching the version that was in effect on their order date. Only orders placed after the change match the new version. The cost to watch is maintaining a non-equi join incrementally (see Design queries for incremental refresh), not the number of orders whose match changes.

If the report needs the segment as of each order date, keep the range join, but isolate it. Join orders to customers in one materialized view, and aggregate in a second materialized view that reads the first.

Don't replace the range join with a join on the current version only to get an equi-join:

JOIN customers_scd2 c
  ON o.customer_id = c.customer_id
  AND c.__END_AT IS NULL

This join changes the results, because every historical order is attributed to the customer's current segment. It also makes changesets larger: each segment change moves all of that customer's past orders to the new segment. Use it only when the report is meant to show current segments.

Decide whether to force incremental refresh

Suppose that the report shows current segments, so it uses the current-version join from the previous step, and that every quarter, the business reassigns most customers to new segments. On those days, nearly every row of the materialized view changes. The customers_scd2 changeset can still be small compared to orders, so the cost model can still choose an incremental refresh.

It is tempting to set REFRESH POLICY INCREMENTAL so that every refresh is incremental. Don't. When nearly every row of the materialized view is affected, an incremental refresh computes the changes for each affected row, deletes the old results, and inserts new ones, which can do more work than rebuilding the table from scratch.

Keep the default AUTO policy, and check the planning_information event and the run time of the update after each reassignment. If the incremental refresh after a reassignment costs more than a full recompute, run REFRESH MATERIALIZED VIEW daily_revenue_by_segment FULL, or a full refresh of the dataset in the pipeline, right after the reassignment. To compare the two techniques, use the run time and Databricks unit (DBU) usage of past incremental and full-recompute updates, for example from flow_progress events and the system.billing.usage table.