Sub topic 5
Creating tables from Python
This chapter assumes you can run PySpark in a Databricks notebook and that you have CREATE TABLE rights on a Unity Catalog schema such as main.sales. It also assumes you know how Delta tables are defined in SQL. Python offers two routes to the same result. You can write a DataFrame to a table, or you can describe the table with the DeltaTable builder.
Writing a DataFrame as a table
saveAsTable registers the table in Unity Catalog by its three-level name. The schema comes from the DataFrame.
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 format, so .format("delta") is optional. Keeping it makes the intent clear.
The save mode decides what happens when the table already exists.
| Mode | Table missing | Table exists |
|---|---|---|
| `errorifexists` (default) | Creates the table | Raises an error |
| `append` | Creates the table | Adds rows |
| `overwrite` | Creates the table | Replaces the data (and the schema, if you pass `overwriteSchema`) |
| `ignore` | Creates the table | Does nothing |
Because append creates the table when it is missing, one job can serve both the first run and every later run.
Know what schema you get
Spark infers the types from your Python values. In the example above, amount becomes DOUBLE, not the DECIMAL(10,2) that the SQL table in the earlier chapter used. order_id becomes BIGINT, and every column is nullable.
If the types matter, state them. Pass an explicit schema to createDataFrame, or cast columns before writing:
from pyspark.sql.functions import col
typed_df = df.withColumn("amount", col("amount").cast("decimal(10,2)"))
typed_df.write.format("delta").mode("overwrite").saveAsTable("main.sales.orders_typed")A DataFrame write cannot declare NOT NULL or CHECK constraints. You add those afterwards with ALTER TABLE, or you create the table first with an explicit definition.
Defining the table first with DeltaTable
The DeltaTable builder creates an empty table with the schema you specify. Use it when the definition should exist before any data arrives.
from delta.tables import DeltaTable
(DeltaTable.createIfNotExists(spark)
.tableName("main.sales.orders")
.addColumn("order_id", "BIGINT", nullable=False)
.addColumn("customer_id", "BIGINT")
.addColumn("order_ts", "TIMESTAMP")
.addColumn("amount", "DECIMAL(10,2)")
.addColumn("status", "STRING")
.execute())This produces the same table as the CREATE TABLE statement from the SQL chapter. The builder has three entry points:
createfails if the table exists.createIfNotExistsdoes nothing if the table exists.createOrReplacereplaces the table definition and its data.
Later writes then have to match this schema. A DataFrame with a different column type or a null order_id is rejected, which is the behavior you want from a defined table.
Running SQL from Python
You can also pass DDL to spark.sql. This helps when you need partitioning, clustering, or constraints, and the call is easy to parameterize:
spark.sql("""
CREATE TABLE IF NOT EXISTS main.sales.events (
event_id BIGINT,
event_date DATE,
payload STRING
) CLUSTER BY (event_date)
""")Choosing between the approaches
| Need | Use |
|---|---|
| Quick table from a transformed DataFrame | `saveAsTable` |
| Exact types and `NOT NULL` before loading | `DeltaTable` builder or `spark.sql` DDL |
| Clustering or constraints in one step | `spark.sql` DDL |
Exercise
A job runs df.write.mode("append").saveAsTable("main.sales.orders_raw") every night. It is run for the first time when the table does not exist. What happens, and what type will a Python float column have?
Show answer
The write succeeds and creates the table, because append creates a missing table. The float column is stored as DOUBLE, since the schema is inferred from the DataFrame. To get DECIMAL(10,2), cast the column before writing or create the table first with an explicit definition.