Sub topic 2
Creating and Updating Delta Lake Tables from Python
Assume you know basic SQL, PySpark DataFrames, Databricks notebooks, and table schemas. This chapter shows how Python creates a Delta table and how SQL changes its data afterward.
Create a table from Python
A DataFrame is an in-memory table. A Delta table stores that data durably with a transaction log. When you use saveAsTable, Databricks registers the table in Unity Catalog.
Define the schema explicitly when column types and nullability matter:
from pyspark.sql import Row
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),
])
orders = 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"),
], schema)
(orders.write
.format("delta")
.mode("overwrite")
.saveAsTable("main.sales.orders"))nullable=False documents and enforces that the DataFrame column cannot contain null values. Add table-level rules with SQL:
spark.sql("""
ALTER TABLE main.sales.orders
ADD CONSTRAINT positive_amount CHECK (amount >= 0)
""")A CHECK constraint rejects any write that violates its condition.
Choose the data layout
Partitioning places rows in separate directory paths. Use it for a low-cardinality column that commonly appears in filters, such as a date. Avoid partitioning by columns with many distinct values.
Liquid clustering organizes data without fixed partition directories. It is often a better choice when query patterns change:
spark.sql("""
CREATE TABLE main.sales.events (
event_id BIGINT,
event_date DATE,
payload STRING
)
USING DELTA
CLUSTER BY (event_date)
""")Do not choose both layouts automatically. Test representative queries and file sizes.
Append and overwrite data
Use append for new rows:
orders.write.format("delta").mode("append").saveAsTable("main.sales.orders")Use overwrite carefully. A selective overwrite limits replacement to matching rows:
(orders.write
.format("delta")
.mode("overwrite")
.option("replaceWhere", "status = 'new'")
.saveAsTable("main.sales.orders"))Change rows with SQL
Delta supports atomic row changes:
spark.sql("""
UPDATE main.sales.orders
SET status = 'shipped'
WHERE order_id = 1001
""")
spark.sql("""
DELETE FROM main.sales.orders
WHERE status = 'cancelled'
""")UPDATE changes matching rows. DELETE removes them. Both create new table versions, so later history and time travel can inspect the changes.
Exercise
Which write mode adds rows without replacing existing table data?
Show answer
append.