Sub topic 16
Saving results as tables
This chapter assumes you can build a DataFrame, aggregate it, and run cells in a Databricks notebook. It covers how to save a result with saveAsTable, what the write modes do, and the errors you are most likely to hit.
Why save a table
A DataFrame lives only as long as your notebook session. A table persists in Unity Catalog, so other notebooks, jobs, and SQL users can query it. Tables you write on Databricks default to Delta format.
Writing a managed table
Use a three-level name: catalog.schema.table.
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",
)
summary = (
orders
.groupBy("customer")
.agg(
F.count("*").alias("order_count"),
F.sum("amount").alias("total_amount"),
)
)
(
summary.write
.mode("overwrite")
.saveAsTable("main.default.customer_summary") # use names you can write to
)saveAsTable is an action, so the whole chain of transformations runs at this point. You need USE CATALOG and USE SCHEMA on the parents, plus CREATE TABLE on the schema.
Choosing a write mode
The mode decides what happens when the table already exists.
| Mode | Behavior if the table exists |
|---|---|
| `errorifexists` (default) | Raises an error |
| `overwrite` | Replaces the table's data |
| `append` | Adds the new rows |
| `ignore` | Does nothing and raises no error |
spark.read.table("main.default.customer_summary").show()Reading the table back is a quick way to confirm the write worked.
Common errors
- Table already exists. You used the default mode on a second run. Pick
overwriteorappendon purpose. - Duplicate rows after rerunning.
appendadds the same rows again each time the cell runs. Useoverwritefor results you recompute in full. - Permission denied. You lack
CREATE TABLEon the schema, orUSEon the catalog. Write to a schema you own. - Schema mismatch on append. The new DataFrame's columns or types differ from the table's. Align them with
selectandcastbefore writing.
Exercise
You run a notebook cell nightly that appends yesterday's recomputed full summary to a table, and the table now has duplicate customers. What change fixes it?
Show answer
Change the mode from append to overwrite. The cell recomputes the full summary each time, so it should replace the table's data instead of adding the same rows again.
Exercise
Which mode makes a second run of the same write cell fail, and why might you want that?
Show answer
errorifexists, the default. It protects an existing table from being changed by accident, so a rerun stops with an error instead of replacing or duplicating data.