Sub topic 16
Saving results as tables
This chapter covers how to persist a DataFrame as a table in Unity Catalog on Databricks. It assumes you can build DataFrames with select, filter and groupBy, and that you know the difference between a transformation and an action. It also assumes you have a catalog and schema where you can create tables. The examples use main.default, so replace that with names you can write to.
Why save a table
A DataFrame lives only as long as your notebook session. When the cluster stops or you detach the notebook, it is gone. A table stores the data and its schema in the metastore, so other notebooks, SQL queries, dashboards and jobs can read it by name.
Writing is an action. Everything you built lazily with transformations runs when saveAsTable executes.
Three-level names
Unity Catalog names a table with three parts: catalog.schema.table. For example, main.default.customer_summary is the table customer_summary in the schema default of the catalog main.
If you leave out the catalog or schema, Databricks uses the session defaults. Fully qualified names are safer in shared notebooks, because the defaults can differ between clusters and users.
Writing with saveAsTable
The write property of a DataFrame returns a DataFrameWriter. You set a save mode, then call saveAsTable.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
summary = (
orders
.groupBy("customer")
.agg(
F.count("*").alias("order_count"),
F.sum("amount").alias("total_amount"),
F.avg("amount").alias("avg_amount"),
)
)
(
summary.write
.mode("overwrite")
.saveAsTable("main.default.customer_summary") # catalog.schema.table; use names you can write to
)A table created this way is a managed table. Databricks chooses the storage location and manages the files, and dropping the table deletes the data. On Databricks, tables written this way default to Delta format, so you do not need to call .format("delta").
Save modes
The mode decides what happens when the table already exists.
| Mode | Behavior if the table exists |
|---|---|
| `error` or `errorifexists` (default) | Raises an error and writes nothing. |
| `overwrite` | Replaces the table contents with the DataFrame. |
| `append` | Adds the DataFrame's rows to the existing rows. |
| `ignore` | Does nothing and raises no error. |
The default is the reason a notebook that works the first time fails when you re-run it. Pick a mode on purpose for each write.
Use overwrite for outputs you can rebuild from scratch, such as a summary. Use append for data that accumulates, such as daily loads. Re-running an append cell adds the same rows again, so the table then holds duplicates.
new_orders = spark.createDataFrame(
[(5, "dave", "2024-03-01", 99.0)],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
).withColumn("order_date", F.to_date("order_date"))
new_orders.write.mode("append").saveAsTable("main.default.orders_history")If orders_history does not exist, append creates it. If it exists, the DataFrame's columns must be compatible with the table's schema.
Schema checks on write
Delta tables enforce their schema. If you append a DataFrame with a column the table lacks, or with an incompatible type, the write fails instead of silently changing the table. This protects downstream readers.
Matching is by column name for most DataFrame writes, so check your column names and types with printSchema() before saving.
If you really intend to change the schema, there are two options:
- With
append, add.option("mergeSchema", "true")to let new columns be added to the table. - With
overwrite, add.option("overwriteSchema", "true")to replace the table's schema along with its data.
Use these deliberately. They change a table that other people may read.
(
summary
.withColumn("loaded_at", F.current_timestamp())
.write
.mode("append")
.option("mergeSchema", "true")
.saveAsTable("main.default.customer_summary")
)Reading the table back
Use spark.table or SQL to confirm the write and to reuse the result.
saved = spark.table("main.default.customer_summary")
saved.printSchema()
display(saved)Because the table is in the metastore, a SQL cell can query it too:
display(spark.sql("SELECT customer, total_amount FROM main.default.customer_summary"))How a write flows
The diagram shows what happens when the action runs.
The commit step matters. A Delta write is atomic, so readers see either the old version of the table or the new one, never a half-written result.
Common errors
- Table already exists. You used the default mode on a second run. Choose
overwriteorappend. - Duplicate rows after a re-run. An
appendcell ran twice. Make loads idempotent, for example by overwriting a partition or merging on a key, or run the append once. - Schema mismatch. The DataFrame has different column names or types than the table. Compare
printSchema()output with the table, and cast withwithColumnandcastif needed. - Permission denied or catalog not found. You lack
CREATE TABLEon the schema orUSEprivileges on the catalog and schema. Ask the owner for access, or write to a schema you own. - Surprising overwrite.
overwritereplaces everything in the table. Check the table name before you run the cell.
Choosing a write strategy
| Situation | Approach |
|---|---|
| Rebuildable summary or report table | `overwrite` |
| Data that grows over time | `append`, with a guard against re-running |
| Table that must change only some rows | A Delta `MERGE`, which this chapter does not cover |
| One-off scratch result | A temporary view, which is not saved |
Exercise
You run a notebook cell with df.write.mode("append").saveAsTable("main.default.daily_sales") and then accidentally run the same cell again. What does the table contain, and how would you change the cell so that a second run does not duplicate data for a one-day load?
Show answer
The table contains the rows twice, because append adds the DataFrame's rows each time. For a rebuildable load you can use overwrite. If the table holds many days, overwrite only that day's data, or merge on a key such as the order ID, so a re-run replaces the rows instead of adding copies.
Exercise
You built a DataFrame with an extra column region and call .write.mode("append").saveAsTable(...) on a table without that column. What happens, and what option lets the write add the column?
Show answer
The write fails with a schema mismatch error, because Delta enforces the table schema. Adding .option("mergeSchema", "true") lets the new column be added to the table. Use it only when the change is intended.