Sub topic 8
Appending and overwriting data
This chapter assumes you can create a Delta table (covered in the earlier chapters on SQL and Python table creation) and that you know what a DataFrame write looks like. It covers the two basic ways to put new data into an existing table: adding rows (append) and replacing rows (overwrite). It also covers selective overwrites, which replace only part of a table, and the mistakes people make most often.
Why these two operations matter
Almost every pipeline ends with a write. The question is what the write should do to rows already in the table.
- Append keeps everything that exists and adds new rows.
- Overwrite removes existing rows and writes new ones, all in one commit.
Both are transactions in the Delta log. Readers either see the table before the write or after it, never a half-written state. An overwrite does not delete the old files straight away. It marks them as removed in the log, so you can still read the previous version with time travel until VACUUM cleans them up.
The examples below use this table:
CREATE TABLE IF NOT EXISTS main.sales.daily_sales (
sale_date DATE,
store_id INT,
revenue DECIMAL(12,2)
) USING DELTA;Appending with SQL
INSERT INTO appends rows. You can supply literal values or a query.
INSERT INTO main.sales.daily_sales VALUES
(DATE'2024-03-01', 1, 120.50),
(DATE'2024-03-01', 2, 98.00);
INSERT INTO main.sales.daily_sales
SELECT sale_date, store_id, revenue
FROM main.sales.daily_sales_staging;Each statement commits as one version, no matter how many rows it inserts. Prefer one large insert to many small ones. Each small insert creates its own commit and at least one small file, which slows later reads until you run OPTIMIZE.
INSERT INTO matches columns by position, not by name. If your SELECT returns store_id, sale_date, revenue, Delta tries to put the store ID into the date column. Either the cast fails or, worse, it succeeds with wrong values. Name the columns you are inserting, or order the SELECT list to match the table:
INSERT INTO main.sales.daily_sales (sale_date, store_id, revenue)
SELECT sale_date, store_id, revenue
FROM main.sales.daily_sales_staging;Columns you leave out of the list are filled with NULL (or their default, if one is defined). A NOT NULL column that is left out makes the statement fail.
Appending with the DataFrame API
In Python, set the write mode to append:
from datetime import date
from decimal import Decimal
batch = spark.createDataFrame(
[
(date(2024, 3, 2), 1, Decimal("133.25")),
(date(2024, 3, 2), 2, Decimal("87.10")),
],
"sale_date date, store_id int, revenue decimal(12,2)",
)
(batch.write
.format("delta")
.mode("append")
.saveAsTable("main.sales.daily_sales"))If the table does not exist, saveAsTable creates it from the DataFrame schema. If it exists, the rows are added.
There is a difference between two similar-looking methods:
| Method | Column matching | Creates the table if missing |
|---|---|---|
| `saveAsTable` with `mode("append")` | By name | Yes |
| `insertInto` | By position | No, the table must exist |
If your DataFrame columns are in a different order from the table, saveAsTable still works. insertInto silently puts values in the wrong columns whenever the types happen to be compatible.
A DataFrame whose schema does not fit the table is rejected. This is schema enforcement, and the chapter on schema evolution covers how to change the table schema on purpose.
Appends are not idempotent
An operation is idempotent if running it twice gives the same result as running it once. A plain append is not. If a job fails after committing and your scheduler retries it, the same rows are added again.
You have three common ways to guard against this:
- Use
MERGE(a later chapter) with a key, so a retry updates rows instead of duplicating them. - Use a selective overwrite (below) keyed on the batch period, so a retry replaces the same slice.
- Use the Delta idempotent-write options
txnAppIdandtxnVersion. Delta records the pair in the log and skips a write if it has already seen that version for that application ID.
(batch.write
.format("delta")
.mode("append")
.option("txnAppId", "daily_sales_loader")
.option("txnVersion", 20240302)
.saveAsTable("main.sales.daily_sales"))Use a version number that increases with each logical batch, such as the batch date as an integer. The same txnVersion must be reused when you retry the same batch, and a later batch must use a higher one.
Overwriting a whole table
A full overwrite replaces all rows in one commit.
INSERT OVERWRITE main.sales.daily_sales
SELECT sale_date, store_id, revenue
FROM main.sales.daily_sales_staging;(batch.write
.format("delta")
.mode("overwrite")
.saveAsTable("main.sales.daily_sales"))Both keep the table's identity: its name, permissions, comments, constraints, and history. The data files change, but the table is the same object.
CREATE OR REPLACE TABLE ... AS SELECT is a different tool. It also replaces the contents, but it lets the schema, properties, and layout change as part of the statement. Use it when the table definition itself is changing. Use INSERT OVERWRITE or mode("overwrite") when only the data changes.
By default, an overwrite must match the existing table schema. If the new data has a different schema and you want it to replace the old one, you must say so:
(batch.write
.format("delta")
.mode("overwrite")
.option("overwriteSchema", "true")
.saveAsTable("main.sales.daily_sales"))overwriteSchema rewrites the schema along with the data. Treat it as a deliberate action, not a way to silence an error.
Selective overwrite with replaceWhere
Often you want to replace only part of a table, such as one day of data being reprocessed. replaceWhere deletes the rows that match a predicate and inserts the new rows in a single atomic commit.
fixed = spark.createDataFrame(
[
(date(2024, 3, 1), 1, Decimal("125.00")),
(date(2024, 3, 1), 2, Decimal("98.00")),
(date(2024, 3, 1), 3, Decimal("45.75")),
],
"sale_date date, store_id int, revenue decimal(12,2)",
)
(fixed.write
.format("delta")
.mode("overwrite")
.option("replaceWhere", "sale_date = '2024-03-01'")
.saveAsTable("main.sales.daily_sales"))The SQL form is INSERT INTO ... REPLACE WHERE:
INSERT INTO main.sales.daily_sales
REPLACE WHERE sale_date = DATE'2024-03-01'
SELECT sale_date, store_id, revenue
FROM main.sales.daily_sales_fixed;Delta checks that every row you write satisfies the predicate. If the DataFrame contains a row for 2024-03-02, the write fails instead of quietly adding a row outside the replaced range. This check protects you from a bad filter upstream. If you see a "data does not conform to the replaceWhere predicate" error, the new data has rows outside the range you named.
Because the write is a delete plus an insert in one commit, it is idempotent. Running the same replacement twice leaves the table in the same state. That makes it a good fit for retryable daily or hourly loads.
Dynamic partition overwrite
If a table is partitioned, you can let the incoming data decide which partitions to replace. Set partitionOverwriteMode to dynamic:
(batch.write
.format("delta")
.mode("overwrite")
.option("partitionOverwriteMode", "dynamic")
.saveAsTable("main.sales.daily_sales_by_date"))Only the partitions that appear in batch are replaced. Other partitions are untouched. This only makes sense on partitioned tables, and it is less explicit than replaceWhere. A single stray row with an unexpected partition value replaces a partition you did not mean to touch. For that reason, replaceWhere is usually the safer choice. Do not set replaceWhere and dynamic partition overwrite on the same write, because Delta rejects the combination.
Choosing the right operation
| Goal | Operation | Retry-safe by itself |
|---|---|---|
| Add new rows | `INSERT INTO`, `mode("append")` | No |
| Replace the whole table's data | `INSERT OVERWRITE`, `mode("overwrite")` | Yes |
| Replace a known slice | `replaceWhere`, `INSERT INTO ... REPLACE WHERE` | Yes |
| Change the table definition and data | `CREATE OR REPLACE TABLE ... AS SELECT` | Yes |
| Update some rows and insert others | `MERGE` | Yes, with a unique key |
Checking what a write did
Every write is a commit, so DESCRIBE HISTORY shows what happened:
DESCRIBE HISTORY main.sales.daily_sales;Look at the operation column (for example WRITE, REPLACE TABLE AS SELECT) and operationMetrics, which reports counts such as numOutputRows and numRemovedFiles. After an overwrite, numRemovedFiles is greater than zero. After a plain append it is zero. This is a quick way to confirm that a job did what you expected.
Common errors
- Duplicate rows after a retry. The load used append without a guard. Switch to
replaceWhere,MERGE, ortxnAppId/txnVersion. - Values in the wrong columns.
INSERT INTOorinsertIntomatched by position. List columns explicitly or usesaveAsTable. - Schema mismatch error on overwrite. The new data has different columns or types. Fix the data, or set
overwriteSchemaif you really mean to change the table. - replaceWhere conformance error. The DataFrame has rows outside the predicate. Filter the DataFrame to the same predicate you pass to
replaceWhere. - Many tiny files after frequent small appends. Batch your writes and run
OPTIMIZEregularly.
Exercise
A nightly job appends yesterday's sales to main.sales.daily_sales. The job failed after the commit but before reporting success, and the scheduler ran it again. What happened to the table, and how would you change the write so a retry is safe?
Show answer
The retry appended the same rows a second time, so yesterday's data is duplicated. To make the job retry-safe, replace yesterday's slice instead of appending, using .mode("overwrite").option("replaceWhere", "sale_date = '<yesterday>'"). Running it twice then gives the same result. Alternatively, keep the append and add txnAppId and txnVersion options, reusing the same txnVersion for the same batch, or use MERGE on a key.
Exercise
You run df.write.format("delta").mode("overwrite").option("replaceWhere", "sale_date = '2024-03-01'").saveAsTable("main.sales.daily_sales"), but df contains rows for both March 1 and March 2. What happens, and why is this behavior useful?
Show answer
The write fails because Delta checks that every row written satisfies the replaceWhere predicate, and the March 2 rows do not. The table is left unchanged. This check stops a wrong upstream filter from adding rows outside the slice you meant to replace.