Delete records from Delta Lake tables
On Databricks, you can locate and delete individual records from your tables, then remove the underlying data from cloud storage. This is useful whenever you need to remove specific data on request or enforce a data retention policy.
Deleting a record is a two-part process: you first delete the record from the table, and then you remove the underlying data files from storage through table maintenance. This article models datasets for an e-commerce company and shows how to delete records in source tables and propagate those changes to downstream tables.
Blueprint for deleting records
The following diagram illustrates how to find, delete, and propagate deleted records across a medallion architecture.

Point deletes with Delta Lake
Delta Lake speeds up point deletes in large tables with ACID transactions, allowing you to locate and remove individual records.
Delta Lake retains table history and makes it available for point-in-time queries and rollbacks. The VACUUM function removes data files that are no longer referenced by a Delta table and are older than a specified retention threshold, permanently deleting the data from storage. To learn more about defaults and recommendations, see Work with table history.
Ensure data is deleted when using deletion vectors
For tables with deletion vectors enabled, a DELETE marks records as removed without immediately rewriting the underlying data files, so the data remains on disk until the files are rewritten and purged. To physically remove the underlying records, run REORG TABLE ... APPLY (PURGE) and then VACUUM. This applies to Delta Lake tables, materialized views, and streaming tables. See Apply soft-deletes to data files.
Delete data in upstream sources
Deleting a record from Databricks does not remove it from data sources outside of Delta Lake, such as Kafka, files, and databases. To completely remove a record, you must also delete it from any upstream sources, such as queues and cloud storage.
Before you delete data, you might need to export workspace data for backup or data portability. See Export workspace data.
Complete deletion is preferable to obfuscation
To remove a record, you can either delete it or obfuscate it, for example, through pseudonymization or data masking. Complete deletion is the safest option, because obfuscation can leave a risk of reidentification.
Delete data in the bronze layer, then propagate to silver and gold layers
Databricks recommends that you delete data in the bronze layer first, driven by a scheduled job that queries a table of deletion requests. After data is deleted from the bronze layer, you can propagate the changes to the silver and gold layers.
Automatically delete rows with auto time-to-live
For tables where rows must be deleted after a specific period, you can use auto time-to-live to automatically delete rows from Unity Catalog managed tables based on a DATE or TIMESTAMP column. Auto time-to-live is powered by predictive optimization and runs DELETE, PURGE, and VACUUM operations in the background. See Automatic row deletion with auto time-to-live.
To turn on auto time-to-live for a streaming table in Lakeflow pipelines, set the auto_ttl parameter in the table definition. The following example adds auto_ttl to the clicks_silver definition from the example pipeline on this page, so the table deletes rows 365 days after their click_timestamp value:
from pyspark import pipelines as dp
from pyspark.sql.functions import col
catalog = "users"
schema = "name"
@dp.table(
name=f"{catalog}.{schema}.clicks_silver",
comment='Cleaned and standardized clicks data',
auto_ttl={"timestamp_column": "click_timestamp", "expire_in_days": 365}
)
@dp.expect_or_drop('valid_click_timestamp', "click_timestamp IS NOT NULL")
def clicks_silver():
return (
spark.readStream
.table(f"{catalog}.{schema}.clicks_bronze")
.withColumn('click_timestamp', col('click_timestamp').cast('timestamp'))
.withWatermark('click_timestamp', '10 minutes')
.dropDuplicates(['click_id'])
.select('click_id', 'user_id', 'url_clicked', 'click_timestamp', 'device_type', 'ip_address')
)
Auto time-to-live removes rows with DELETE commits, so the table is no longer append-only. Before you turn on auto time-to-live, set skipChangeCommits on every streaming read of the table, including streaming tables that read from it. Without this option, the stream fails when auto time-to-live first deletes rows. See Handle changes to source Delta Lake tables.
In the example pipeline, user_clicks_silver streams from clicks_silver, so update that read before you add auto_ttl:
clicks = spark.readStream \
.option('skipChangeCommits', 'true') \
.table('clicks_silver')
skipChangeCommits ignores the delete commits, so rows that auto time-to-live deletes from a source table remain in downstream streaming tables. Delete them from those tables separately. See Propagate changes from bronze to silver and gold layers.
Auto time-to-live deletion occurs asynchronously and exact timing is not guaranteed. The buffer between row expiration and permanent removal can be up to 6 days plus the value of the data retention table property, which defaults to 7 days. Verify deletion before you treat the data as removed. See System tables.
Regularly maintain tables to remove data from historical files
By default, Delta Lake retains table history for 30 days. Time travel is available within the deleted file retention period, which is 7 days by default. Deleting a record does not immediately remove it from storage. The data files that back previous table versions still contain the record and remain in cloud storage until you run maintenance to remove them. By default, VACUUM only removes data files that are older than 7 days. As a result, deleted records can remain recoverable through time travel until those files pass the retention threshold and are vacuumed. Therefore, you should regularly maintain datasets to remove previous versions of data. The recommended way is Predictive optimization for Unity Catalog managed tables, which intelligently maintains both streaming tables and materialized views.
- For tables managed by predictive optimization, Lakeflow pipelines intelligently maintain both streaming tables and materialized views, based on usage patterns.
- For tables without predictive optimization enabled, Lakeflow pipelines automatically perform maintenance tasks within 24 hours of streaming tables and materialized views being updated.
If you are not using predictive optimization or Lakeflow pipelines, run a VACUUM command on Delta tables to permanently remove previous versions of data. By default, this reduces the time travel capabilities to 7 days, which is a configurable setting, and removes historical versions of the data in question from cloud storage too.
Delete records from the bronze layer
Depending on the design of your lakehouse, you might be able to sever the link between identifying and non-identifying user data. For example, if you use a non-natural key such as user_id instead of a natural key like email, you can delete the identifying data and leave other data in place.
The rest of this article deletes complete user records from all bronze tables. You can delete records by running a DELETE command, as shown in the following code:
spark.sql("DELETE FROM bronze.users WHERE user_id = 5")
When you delete a large number of records at one time, Databricks recommends using the MERGE command. The following code assumes that you have a control table called deletion_control_table that contains a user_id column. You insert a record into this table for every user whose data must be deleted.
The MERGE command specifies the condition for matching rows. In this example, it matches records from target_table with records in deletion_control_table based on the user_id. If there is a match (for example, a user_id in both the target_table and the deletion_control_table), the row in the target_table is deleted. After this MERGE command is successful, update the control table to confirm that the request has been processed.
spark.sql("""
MERGE INTO target
USING (
SELECT user_id
FROM deletion_control_table
) AS source
ON target.user_id = source.user_id
WHEN MATCHED THEN DELETE
""")
Propagate changes from bronze to silver and gold layers
After data is deleted in the bronze layer, you must propagate the changes to tables in the silver and gold layers.
Materialized views: Automatically handle deletions
Materialized views automatically handle deletions in sources. Hence, you do not have to do anything special to ensure that a materialized view does not contain data that has been deleted from a source. You must refresh a materialized view and run maintenance to ensure that deletions are completely processed.
A materialized view always returns the correct result because it uses incremental computation if it is cheaper than full recomputation, but never at the cost of correctness. In other words, deleting data from a source could cause a materialized view to fully recompute.

Streaming tables: Delete data and read the streaming source using skipChangeCommits
Streaming tables process append-only data when they stream from Delta table sources. Any other operation, such as updating or deleting a record from a streaming source, is not supported and breaks the stream.
For a more robust streaming implementation, stream from the change feeds of Delta tables instead, and handle updates and deletes in your processing code. See Handle changes to source Delta Lake tables.

Because streaming from Delta tables handles new data only, you must handle changes to data yourself. The recommended method is to: (1) delete data in the source Delta tables using DML, (2) delete data from the streaming table using DML, and then (3) update the streaming read to use skipChangeCommits. This flag indicates that the streaming table should skip anything other than inserts, such as updates or deletes.

Alternatively, you can (1) delete data from the source, then (2) fully refresh the streaming table. When you fully refresh a streaming table, it clears the table's streaming state and reprocesses all data again. Any upstream data source that is beyond its retention period (for example, a Kafka topic that ages out data after 7 days) won't be processed again, which could cause data loss. We recommend this option for streaming tables only in the scenario where historical data is available and processing it again won't be costly.

Example: Delete user records for an e-commerce company
The following diagram shows a medallion architecture for an e-commerce company where user records need to be deleted. Even though a user's data is deleted, you might want to count their activities in downstream aggregations.

- Source tables
source_users- A streaming source table of users (created here, for the example). Production environments typically use Kafka, Kinesis, or similar streaming platforms.source_clicks- A streaming source table of clicks (created here, for the example). Production environments typically use Kafka, Kinesis, or similar streaming platforms.
- Control table
deletion_requests- Control table containing user IDs whose data must be deleted. When a user requests deletion, add them here.
- Bronze layer
users_bronze- User dimensions. Contains identifying data (for example, email address).clicks_bronze- Click events. Contains identifying data (for example, IP address).
- Silver layer
clicks_silver- Cleaned and standardized clicks data.users_silver- Cleaned and standardized user data.user_clicks_silver- Joinsclicks_silver(streaming) with a snapshot ofusers_silver.
- Gold layer
user_behavior_gold- Aggregated user behavior metrics.marketing_insights_gold- User segment for market insights.
Step 1: Populate tables with sample data
The following code creates these two tables for this example and populates them with sample data:
source_userscontains dimensional data about users. This table contains an identifying column calledemail.source_clickscontains event data about activities performed by users. It contains an identifying column calledip_address.
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, MapType, DateType
catalog = "users"
schema = "name"
# Create table containing sample users
users_schema = StructType([
StructField('user_id', IntegerType(), False),
StructField('username', StringType(), True),
StructField('email', StringType(), True),
StructField('registration_date', StringType(), True),
StructField('user_preferences', MapType(StringType(), StringType()), True)
])
users_data = [
(1, 'alice', 'alice@example.com', '2021-01-01', {'theme': 'dark', 'language': 'en'}),
(2, 'bob', 'bob@example.com', '2021-02-15', {'theme': 'light', 'language': 'fr'}),
(3, 'charlie', 'charlie@example.com', '2021-03-10', {'theme': 'dark', 'language': 'es'}),
(4, 'david', 'david@example.com', '2021-04-20', {'theme': 'light', 'language': 'de'}),
(5, 'eve', 'eve@example.com', '2021-05-25', {'theme': 'dark', 'language': 'it'})
]
users_df = spark.createDataFrame(users_data, schema=users_schema)
users_df.write.mode("overwrite").saveAsTable(f"{catalog}.{schema}.source_users")
# Create table containing clickstream (i.e. user activities)
from pyspark.sql.types import TimestampType
clicks_schema = StructType([
StructField('click_id', IntegerType(), False),
StructField('user_id', IntegerType(), True),
StructField('url_clicked', StringType(), True),
StructField('click_timestamp', StringType(), True),
StructField('device_type', StringType(), True),
StructField('ip_address', StringType(), True)
])
clicks_data = [
(1001, 1, 'https://example.com/home', '2021-06-01T12:00:00', 'mobile', '192.168.1.1'),
(1002, 1, 'https://example.com/about', '2021-06-01T12:05:00', 'desktop', '192.168.1.1'),
(1003, 2, 'https://example.com/contact', '2021-06-02T14:00:00', 'tablet', '192.168.1.2'),
(1004, 3, 'https://example.com/products', '2021-06-03T16:30:00', 'mobile', '192.168.1.3'),
(1005, 4, 'https://example.com/services', '2021-06-04T10:15:00', 'desktop', '192.168.1.4'),
(1006, 5, 'https://example.com/blog', '2021-06-05T09:45:00', 'tablet', '192.168.1.5')
]
clicks_df = spark.createDataFrame(clicks_data, schema=clicks_schema)
clicks_df.write.format("delta").mode("overwrite").saveAsTable(f"{catalog}.{schema}.source_clicks")
Step 2: Create a pipeline that processes user data
The following code creates bronze, silver, and gold layers of the medallion architecture shown above.
from pyspark import pipelines as dp
from pyspark.sql.functions import col, concat_ws, count, countDistinct, avg, when, expr
catalog = "users"
schema = "name"
# ----------------------------
# Bronze Layer - Raw Data Ingestion
# ----------------------------
@dp.table(
name=f"{catalog}.{schema}.users_bronze",
comment='Raw users data loaded from source'
)
def users_bronze():
return (
spark.readStream.table(f"{catalog}.{schema}.source_users")
)
@dp.table(
name=f"{catalog}.{schema}.clicks_bronze",
comment='Raw clicks data loaded from source'
)
def clicks_bronze():
return (
spark.readStream.table(f"{catalog}.{schema}.source_clicks")
)
# ----------------------------
# Silver Layer - Data Cleaning and Enrichment
# ----------------------------
dp.create_streaming_table(
name=f"{catalog}.{schema}.users_silver",
comment='Cleaned and standardized users data'
)
@dp.view
@dp.expect_or_drop('valid_email', "email IS NOT NULL")
def users_bronze_view():
return (
spark.readStream
.table(f"{catalog}.{schema}.users_bronze")
.withColumn('registration_date', col('registration_date').cast('timestamp'))
.dropDuplicates(['user_id', 'registration_date'])
.select('user_id', 'username', 'email', 'registration_date', 'user_preferences')
)
dp.create_auto_cdc_flow(
target=f"{catalog}.{schema}.users_silver",
source="users_bronze_view",
keys=["user_id"],
sequence_by="registration_date",
)
@dp.table(
name=f"{catalog}.{schema}.clicks_silver",
comment='Cleaned and standardized clicks data'
)
@dp.expect_or_drop('valid_click_timestamp', "click_timestamp IS NOT NULL")
def clicks_silver():
return (
spark.readStream
.table(f"{catalog}.{schema}.clicks_bronze")
.withColumn('click_timestamp', col('click_timestamp').cast('timestamp'))
.withWatermark('click_timestamp', '10 minutes')
.dropDuplicates(['click_id'])
.select('click_id', 'user_id', 'url_clicked', 'click_timestamp', 'device_type', 'ip_address')
)
@dp.table(
name=f"{catalog}.{schema}.user_clicks_silver",
comment='Joined users and clicks data on user_id'
)
def user_clicks_silver():
# Read users_silver as a static DataFrame - each refresh
# will use a snapshot of the users_silver table.
users = spark.read.table(f"{catalog}.{schema}.users_silver")
# Read clicks_silver as a streaming DataFrame.
clicks = spark.readStream \
.table('clicks_silver')
# Perform the join - join of a static dataset with a
# streaming dataset creates a streaming table.
joined_df = clicks.join(users, on='user_id', how='inner')
return joined_df
# ----------------------------
# Gold Layer - Aggregated and Business-Level Data
# ----------------------------
@dp.materialized_view(
name=f"{catalog}.{schema}.user_behavior_gold",
comment='Aggregated user behavior metrics'
)
def user_behavior_gold():
df = spark.read.table(f"{catalog}.{schema}.user_clicks_silver")
return (
df.groupBy('user_id')
.agg(
count('click_id').alias('total_clicks'),
countDistinct('url_clicked').alias('unique_urls')
)
)
@dp.materialized_view(
name=f"{catalog}.{schema}.marketing_insights_gold",
comment='User segments for marketing insights'
)
def marketing_insights_gold():
df = spark.read.table(f"{catalog}.{schema}.user_behavior_gold")
return (
df.withColumn(
'engagement_segment',
when(col('total_clicks') >= 100, 'High Engagement')
.when((col('total_clicks') >= 50) & (col('total_clicks') < 100), 'Medium Engagement')
.otherwise('Low Engagement')
)
)
Step 3: Delete data in source tables
In this step, you delete data in all tables where a user's data is found. The following function removes all instances of a user's data from tables that contain it.
catalog = "users"
schema = "name"
def apply_delete(user_id):
tables_with_user_data = ["source_users", "source_clicks", "clicks_bronze", "users_bronze", "clicks_silver", "users_silver", "user_clicks_silver"]
for table in tables_with_user_data:
print(f"Deleting user_id {user_id} from table {table}")
spark.sql(f"""
DELETE FROM {catalog}.{schema}.{table}
WHERE user_id = {user_id}
""")
# Purge soft-deleted rows. Required for tables with deletion vectors enabled.
spark.sql(f"REORG TABLE {catalog}.{schema}.{table} APPLY (PURGE)")
REORG TABLE ... APPLY (PURGE) rewrites the data files, but the old files remain in storage until VACUUM removes them after the retention threshold. Predictive optimization and Lakeflow pipelines maintenance run VACUUM for you. Otherwise, run VACUUM on each table. See Regularly maintain tables to remove data from historical files.
In this example the source tables are Delta tables. In production, sources are typically Kafka, Kinesis, or similar systems, so delete the data there as well. See Delete data in upstream sources.
Step 4: Add skipChangeCommits to definitions of affected streaming tables
In this step, you must tell the pipeline to skip non-append rows. Add the skipChangeCommits option to the following methods. You don't have to update the definitions of materialized views because they automatically handle updates and deletes.
users_bronzeusers_silverclicks_bronzeclicks_silveruser_clicks_silver
The following code shows how to update the users_bronze method:
def users_bronze():
return (
spark.readStream.option('skipChangeCommits', 'true').table(f"{catalog}.{schema}.source_users")
)
When you run the pipeline again, the update succeeds.