Sub topic 5
Creating tables from Python
This chapter assumes you can write the SQL CREATE TABLE and CTAS statements from the previous chapter. It also assumes you can run PySpark in a Databricks notebook with compute attached, and that you have CREATE TABLE privileges on a Unity Catalog schema such as main.sales. The examples use the spark session that Databricks notebooks provide.
Three ways to create a table from Python
Python offers three routes to a Delta table. Each fits a different situation.
- DataFrame writer:
df.write.saveAsTable(...)creates the table from a DataFrame, and the table takes the DataFrame's schema. - DeltaTable builder:
DeltaTable.create(...)and its variants declare columns, nullability, comments and properties before any data exists. spark.sql: this runs any DDL statement as a string, which is useful when you already have the SQL or need syntax the builder lacks.
All three produce the same kind of object, a Delta table registered in Unity Catalog with a transaction log. The difference is where the schema comes from. With the writer, the data decides. With the builder or SQL, you decide.
Creating a table with the DataFrame writer
The simplest route builds a DataFrame and saves it under a three-level name, catalog.schema.table.
from pyspark.sql import Row
df = spark.createDataFrame([
Row(order_id=1001, customer_id=1, amount=25.50, status="new"),
Row(order_id=1002, customer_id=2, amount=40.00, status="new"),
])
df.write.format("delta").mode("append").saveAsTable("main.sales.orders_raw")On Databricks, Delta is the default table format. The .format("delta") call is therefore optional, but it makes the intent explicit and protects the code if it runs elsewhere.
saveAsTable registers the table in the metastore. If the table does not exist, it is created. If it does exist, the save mode decides what happens.
| Mode | Table does not exist | Table exists |
|---|---|---|
| `errorifexists` (default) | Creates it | Raises an error |
| `append` | Creates it | Adds the rows |
| `overwrite` | Creates it | Replaces the data (the next chapter covers this) |
| `ignore` | Creates it | Does nothing, with no error |
The schema comes from the DataFrame
With this route you get whatever types Spark inferred. In the example above, amount=25.50 becomes DOUBLE, not DECIMAL(10,2). Floating-point types are a poor fit for money, and a table created this way keeps that type until you change it.
You can check what was created:
spark.table("main.sales.orders_raw").printSchema()Every column from a DataFrame is created as nullable. The writer cannot express NOT NULL, so a table created by saveAsTable has no constraints. You can add them afterwards with ALTER TABLE, which later chapters cover.
Declaring the schema explicitly
To control types, pass an explicit schema when you build the DataFrame. Inference then no longer matters.
from decimal import Decimal
from pyspark.sql.types import (
StructType, StructField, LongType, DecimalType, StringType
)
schema = StructType([
StructField("order_id", LongType(), nullable=False),
StructField("customer_id", LongType(), nullable=True),
StructField("amount", DecimalType(10, 2), nullable=True),
StructField("status", StringType(), nullable=True),
])
rows = [
(1001, 1, Decimal("25.50"), "new"),
(1002, 2, Decimal("40.00"), "new"),
]
typed_df = spark.createDataFrame(rows, schema)
typed_df.write.format("delta").mode("overwrite").saveAsTable("main.sales.orders_typed")Use Decimal values for DecimalType columns. Passing Python floats raises a type error. The nullable=False flag on order_id helps Spark's planning but does not make the saved column NOT NULL. To get a real constraint, use the builder or SQL, as shown next.
Creating a table with the DeltaTable builder
The DeltaTable builder creates the table before any data is loaded. It is the closest Python equivalent of a SQL CREATE TABLE statement with a column list.
from delta.tables import DeltaTable
(DeltaTable.createIfNotExists(spark)
.tableName("main.sales.customers")
.addColumn("customer_id", "BIGINT", nullable=False)
.addColumn("name", "STRING")
.addColumn("email", "STRING", comment="Contact address")
.addColumn("created_at", "TIMESTAMP")
.comment("One row per customer")
.property("delta.enableChangeDataFeed", "true")
.execute())The builder has three entry points:
| Method | Behavior if the table exists |
|---|---|
| `DeltaTable.create(spark)` | Raises an error |
| `DeltaTable.createIfNotExists(spark)` | Leaves the table unchanged |
| `DeltaTable.createOrReplace(spark)` | Replaces the definition and the data |
Nothing happens until you call .execute(). Forgetting it is a common mistake. The cell runs without error and no table appears.
addColumn takes the column name, a type given as a string or a DataType, and an optional nullable flag that defaults to True. With nullable=False, the column is created NOT NULL, and later writes that contain nulls in it fail. It also accepts comment, generatedAlwaysAs and generatedByDefaultAs for generated columns.
Other builder methods:
.comment(text)sets the table comment..property(key, value)sets a table property..partitionedBy("col", ...)sets Hive-style partition columns..location(path)makes the table external.
The Delta Lake version on your runtime determines whether the builder also offers .clusterBy(...) for liquid clustering. If it does not, create the table with SQL instead:
spark.sql("""
CREATE TABLE IF NOT EXISTS main.sales.events (
event_id BIGINT,
event_date DATE,
payload STRING
) CLUSTER BY (event_date)
""")createOrReplace deserves care. It drops the previous contents, which is rarely what you want in a scheduled job. Delta keeps the old versions in history, so you can recover them with RESTORE until VACUUM removes the files. Even so, treat it as destructive.
Managed and external tables from Python
Without a location, both routes create a managed table. Unity Catalog stores the files in the schema's managed storage location and deletes them when you drop the table.
To create an external table, give a location that Unity Catalog governs through an external location. With the builder, call .location(...):
(DeltaTable.createIfNotExists(spark)
.tableName("main.sales.orders_ext")
.addColumn("order_id", "BIGINT", nullable=False)
.addColumn("amount", "DECIMAL(10,2)")
.location("abfss://[email protected]/sales/orders_ext")
.execute())With the writer, pass the path as an option:
(typed_df.write
.format("delta")
.mode("append")
.option("path", "abfss://[email protected]/sales/orders_typed_ext")
.saveAsTable("main.sales.orders_typed_ext"))Replace the storage URI with a path your workspace has an external location for. Without that, the call fails with a permissions error.
Path-based writes versus named tables
You may see code like df.write.format("delta").save("/some/path"). It writes Delta files but registers no table, so you cannot query the data by name, and Unity Catalog cannot govern it as a table. In new code, prefer saveAsTable or the builder. To read a path-based Delta directory, use DeltaTable.forPath or spark.read.format("delta").load(path). To get a handle on a registered table, use DeltaTable.forName(spark, "main.sales.orders").
Common errors
- Table already exists.
saveAsTablewith the default mode fails when the table exists. Add.mode("append")or.mode("overwrite"), or usecreateIfNotExists. - Nothing was created. A builder chain without
.execute()does not run. - Unexpected types. Floats become
DOUBLE, and Python integers becomeBIGINT. Declare the schema when exact types matter. - Column mismatch on append.
saveAsTablematches columns by name, whereasinsertIntomatches by position. If the DataFrame has columns the table lacks, the write fails unless you enable schema evolution, which a later chapter covers. - Three-part name errors. If you omit the catalog, Spark uses your session's current catalog and schema. Run
spark.sql("SELECT current_catalog(), current_schema()").show()to see which. Fully qualified names avoid surprises.
Exercise
You run this cell twice in a notebook and the second run fails. Why, and what are two ways to fix it? df.write.format("delta").saveAsTable("main.sales.daily_totals")
Show answer
The default save mode is errorifexists, so the second run raises an error because the table already exists. Fix it by adding .mode("append") to add the new rows, or .mode("overwrite") to replace the contents. Alternatively, create the table once with DeltaTable.createIfNotExists(spark)...execute() and write to it with an explicit mode afterwards.
Exercise
A teammate builds a table with DeltaTable.createIfNotExists(spark).tableName("main.sales.refunds").addColumn("refund_id", "BIGINT", nullable=False).addColumn("amount", "DECIMAL(10,2)") and runs the cell. No table appears. What is missing, and how does refund_id behave once the table exists?
Show answer
The chain is missing .execute(), so nothing runs. After the call is added, refund_id is created as NOT NULL, so any write that contains a null refund_id fails. amount is nullable.