Spark SQL and DataFrames together
Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:20 on Thursday. Last night the job that counts the views of one product page read all 4 TB of the events table to keep one product's rows. A teammate has a fix ready: rewrite the DataFrame code as one big SQL query, "because SQL is faster in Spark". Nora opens the plan instead.
You'll learn to
- Mix SQL and DataFrame code in one job with temp views
- Explain why neither SQL nor the DataFrame API is faster
- Show from a plan why a Python UDF is slow
- Handle bad values under ANSI mode with the try_ functions
Learn
SQL and DataFrame code share a job
First: can the two even mix? Yes. orders.createOrReplaceTempView('orders') gives a DataFrame a name that SQL can use, called a temp view. spark.sql('SELECT ... FROM orders') then returns an ordinary DataFrame, which you keep transforming with the API or register as another view.
Nothing is copied. A view is a named plan: when an action runs, Spark reads the source as it would for the DataFrame itself. The view lives only in your SparkSession and disappears when the session ends. A permanent table is a different thing (saveAsTable, Module 13).
Use createOrReplaceTempView: run the cell twice and it replaces the view, where createTempView would fail because the name already exists.
SQL in, DataFrame out
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
orders.createOrReplaceTempView("orders")
items.createOrReplaceTempView("order_items")
by_status = spark.sql("""
SELECT o.status,
COUNT(DISTINCT o.order_id) AS orders,
ROUND(SUM(i.qty * i.unit_price), 2) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
GROUP BY o.status
""")
# ...and carry on with the DataFrame API
open_revenue = by_status.filter(F.col("status").isin("placed", "shipped"))
for r in open_revenue.orderBy("status").collect():
print(r["status"], r["orders"], r["revenue"])
Read it top to bottom: two views, one SQL query, then a filter from the API on the result of that query.
Two ways in, one plan out
So is the SQL version faster? Nora follows both versions into the engine.
Spark's optimiser is called Catalyst. It turns SQL text and DataFrame code into the same thing: a logical plan, a tree of steps such as scan, filter, join and aggregate. Catalyst improves that plan (it pushes filters down and drops unused columns), then picks a physical plan, the steps that really run.
A query written in SQL and the same query written with groupBy and join end up as the same physical plan. Module 12 shows how to read that plan with explain().
Two front doors, one engine
A SQL query and DataFrame code on the left both flow into one logical plan, which Catalyst optimises and turns into one physical plan.
Follow both arrows from the left: they meet at the logical plan, and everything after it is shared.
Remember: SQL and DataFrame code are two ways to write one plan. Neither is faster.
Choose by people, not by speed
With speed equal, the choice is about people and code. SQL reads like a report, and analysts and dbt users can review it. The DataFrame API is Python: you can put steps in functions, loop over a list of columns, and test on small DataFrames.
Most teams mix freely. On Databricks a %sql cell in a Python notebook can query the temp views your Python cells created. SQL, often as dbt models, holds the transformations everyone reviews. Python does the reading, the writing, the loops over many tables and the tests.
When each one fits best
| Spark SQL | DataFrame API |
|---|---|
| Set logic that reads like a report: joins, groups, CTEs | Steps you build in functions and reuse across jobs |
| Analysts and dbt users can review it | Loops over a list of columns or tables, with no string building |
| Easy to paste into a %sql cell or a SQL warehouse | Unit tests on small DataFrames (Module 7) |
| Values glued in with f-strings are risky | Typos in column names show up in your editor and in tests |
Do not glue values into SQL text. spark.sql(f"SELECT * FROM orders WHERE status = '{status}'") breaks on a quote in the value and, with user input, is SQL injection. Filter with the API (F.col("status") == status), or use parameters, which Spark 3.4 and later accept: spark.sql("SELECT * FROM orders WHERE status = :s", args={"s": status}).
One column per status, from a list
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
# One column per status, from a list: easy in the API, clumsy in SQL text
statuses = ["delivered", "returned", "cancelled"]
counts = [F.sum(F.when(F.col("status") == s, 1).otherwise(0)).alias(s) for s in statuses]
per_customer = orders.groupBy("customer_id").agg(*counts)
print(per_customer.columns)
print(per_customer.filter(F.col("customer_id") == 3).first())
# A SQL snippet inside the API: F.expr
state = orders.select(F.expr("CASE WHEN status IN ('placed', 'shipped') THEN 'open' ELSE 'closed' END").alias("state"))
print([(r["state"], r["count"]) for r in state.groupBy("state").count().orderBy("state").collect()])
A loop like this is easy in the API and clumsy in SQL text. F.expr accepts any Spark SQL expression, for when SQL says it more clearly. Real PySpark also has df.selectExpr("..."); the browser engine does not, so use F.expr inside select.
The slow part is a Python function
Back to the slow job. Nora points at one line of its plan: BatchEvalPython. The job calls product_from_page, a Python function wrapped as a UDF (user-defined function, F.udf(my_function)) so Spark can call it on a column.
Spark's engine runs in the JVM, and the JVM cannot run Python. So each executor starts Python worker processes, and every task ships its rows across to a worker and waits for the answers. Think of a factory line where every part is boxed, driven to a second building for one step, and driven back.
The built-in functions in F never make that trip.
One batch crosses to Python and back
A task in the JVM scans rows, serializes a batch of values and sends it to a Python worker, which calls the function on each row and sends the results back to be joined onto the rows.
Inside the engine. The task scans rows and runs Spark's generated Java code up to the UDF. A built-in such as
whenorregexp_extractwould finish right here.The batch leaves. The task serializes a batch of
pagevalues (turns them into bytes) and sends it across. A plain UDF pickles rows, Python's own byte format (BatchEvalPython). A pandas UDF sends Apache Arrow column batches of up to 10,000 rows (ArrowEvalPython).Python does the work. The worker turns the bytes into Python objects and calls the function once per row. Its memory sits outside the JVM heap, inside the executor's overhead (Lesson 12.11 explains both).
The results come back. The worker serializes the answers and the task joins them onto its rows. Every value has been converted twice. Then the next batch starts, for every batch of every task.
Arrow makes the crossing cheaper, not free: a built-in function never leaves the left-hand box.
The UDF in the plan (Databricks)
Runs on Databricks:
from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType
@F.udf(returnType=IntegerType())
def product_from_page(page):
if page and page.startswith("/p/"):
return int(page[3:])
return None
events.select("event_id", product_from_page("page").alias("product_id")).explain()
== Physical Plan ==
*(2) Project [event_id#0, pythonUDF0#21 AS product_id#15]
+- BatchEvalPython [product_from_page(page#4)#14], [pythonUDF0#21]
+- FileScan json [event_id#0,page#4] ...
BatchEvalPython is the step where rows leave the engine for a Python worker (ArrowEvalPython when Arrow is used). Output trimmed; the numbers after # change every run. The browser engine has no UDFs at all, a good reason to practise the built-in way.
Why the scan read all 4 TB
The round trip is half the cost. The other half is what Catalyst can no longer do.
To Catalyst a Python UDF is a black box with a name. Take filter(product_from_page('page') == 104). Normally Spark hands a filter to the file reader, so the reader can skip data. That is called pushdown. But the reader cannot run Python, so the filter stays above the UDF and the Parquet reader gets PushedFilters: []. No partition pruning, no row-group skipping: every byte is read.
The same idea as a built-in, F.col('page') == '/p/104', is pushed into the scan.
The same filter, as a UDF and as a built-in
Two plan trees for the same query: with a Python UDF the filter sits above BatchEvalPython and the Parquet scan has no pushed filters; with a built-in comparison the Python step is gone and the filter is pushed into the scan.
With the UDF. Read from the bottom up. The scan has nothing to filter by, so it reads all 4 TB. Every row is shipped to Python, and only then does the filter run.
With a built-in comparison. The Python step is gone, and the scan shows
PushedFilters: [IsNotNull(page), EqualTo(page,/p/104)]. Parquet min/max statistics can now skip whole row groups (Lesson 4.5).
Same answer both times; how many bytes step 2 reads depends on how the data is laid out, not on Python.
Say it with built-in functions
A UDF also stops two quieter optimisations. Catalyst cannot simplify what it cannot read: constant folding (working out 2 * 60 once, not per row), null propagation and filter reordering all need to know what an expression does. And Spark normally fuses a chain of steps into one Java loop (whole-stage code generation); a Python step splits the stage around it.
So the fix is rarely a faster UDF. It is no UDF. The functions in F (when, regexp_extract, split, to_date, hundreds more) run in the generated Java code with no crossing at all. If nothing built-in fits, use a pandas UDF (@F.pandas_udf): it still crosses, but in Arrow batches.
The same logic with built-in functions
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
events = spark.read.json("data/events.jsonl")
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
# Instead of a UDF that parses "/p/104": a regular expression, run by the engine
views = (
events.filter(F.col("type") == "product_view")
.withColumn("product_id", F.regexp_extract("page", r"^/p/(\d+)$", 1).cast("int"))
)
top = views.groupBy("product_id").agg(F.count("*").alias("views")).orderBy(F.desc("views"), "product_id")
print([(r["product_id"], r["views"]) for r in top.limit(3).collect()])
# Instead of a UDF with if/elif: when / otherwise
per_order = items.groupBy("order_id").agg(F.round(F.sum(F.col("qty") * F.col("unit_price")), 2).alias("revenue"))
banded = per_order.withColumn(
"band",
F.when(F.col("revenue") >= 150, "large").when(F.col("revenue") >= 50, "medium").otherwise("small"),
)
print([(r["band"], r["count"]) for r in banded.groupBy("band").count().orderBy("band").collect()])
Two rewrites to read: a regular expression instead of the UDF that parsed /p/104, and when/otherwise instead of a UDF full of if/elif.
Remember: a built-in function stays inside the engine. A Python UDF sends every row out and back, and hides the filter from the scan.
Spark 4 stops hiding bad values
One more thing SQL and the API share: the rules for bad values. Take a quantity that arrives as the text N/A, and cast it to a number.
Up to Spark 3.5 the cast quietly returned null. In Spark 4.0 the setting spark.sql.ansi.enabled is true by default, and bad input fails the query instead. A job that ran for years on 3.5 can fail on its first night on 4.0, on the same data.
Do not switch ANSI off for the whole job. Decide per column: the try_ functions (try_cast, try_divide, try_add, try_element_at) keep the old null where you want it. Then count the nulls they produce.
The same expression, before and after ANSI mode
| Expression | Spark 3.5 (ANSI off) | Spark 4.0 (ANSI on) |
|---|---|---|
| CAST('N/A' AS INT) | null | CASTINVALIDINPUT (SQLSTATE 22018) |
| Integer overflow | wraps around to a negative number | ARITHMETICOVERFLOW (22003) |
| x / 0 | null | DIVIDEBYZERO (22012) |
| An array index out of range | no error | INVALIDARRAYINDEX |
Type coercion follows stricter ANSI rules too.
The same two lines on Spark 3.5 and Spark 4.0
Runs on Databricks:
from pyspark.sql import functions as F
raw = spark.createDataFrame([("5",), ("N/A",)], "qty STRING")
raw.select(F.col("qty").cast("int").alias("qty")).collect()
nums = spark.createDataFrame([(7, 0)], "a INT, b INT")
nums.select((F.col("a") / F.col("b")).alias("r")).collect()
# Spark 3.5 (ANSI off): [Row(qty=5), Row(qty=None)] and [Row(r=None)]
# Spark 4.0 (ANSI on):
[CAST_INVALID_INPUT] The value 'N/A' of the type "STRING" cannot be cast to "INT" because it is malformed. Correct the value as per the syntax, or change its target type. Use `try_cast` to tolerate malformed input and return NULL instead. SQLSTATE: 22018
[DIVIDE_BY_ZERO] Division by zero. Use `try_divide` to tolerate divisor being 0 and return NULL instead. If necessary set "spark.sql.ansi.enabled" to "false" to bypass this error. SQLSTATE: 22012
Output trimmed to the messages. Each message names its own fix: reach for try_cast on the one column that needs it, not for the global switch.
One bad quantity, three ways
Three text quantities, 5, N/A and null, are cast to integers three ways: a plain cast on Spark 3.5 hides the bad value as null, a plain cast on Spark 4.0 fails the query, and try_cast returns null on purpose.
A plain cast on Spark 3.5.
N/Aturns into null with no message. In the result it looks the same as the quantity that was missing all along.A plain cast on Spark 4.0. The same line stops the query with
CAST_INVALID_INPUT. The bad value is visible now, and nothing is loaded.try_cast, on purpose.N/Abecomes null again, but now you chose it. Send that row to a quarantine table and count it, so every null is accounted for.
Watch the middle row: the same bad value is hidden, then loud, then handled.
try_cast and try_divide in the browser
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()
raw = spark.createDataFrame([("5",), ("N/A",), (None,)], "qty STRING")
print([r["q"] for r in raw.select(F.expr("try_cast(qty AS INT)").alias("q")).collect()])
nums = spark.createDataFrame([(10, 2), (7, 0)], "a INT, b INT")
print([r["r"] for r in nums.select(F.try_divide("a", "b").alias("r")).collect()])
try:
raw.select(F.col("qty").cast("int").alias("q")).collect()
print("plain cast: nulls")
except Exception as e:
print("plain cast failed:", type(e).__name__)
The browser engine mixes the two worlds: its plain cast fails on N/A the way Spark 4.0 does (DuckDB's error, not Spark's), while its plain division by zero returns null the way 3.5 does. try_cast and try_divide behave the same everywhere.
Numbers to remember
| Name | Default or version | What to know |
|---|---|---|
| spark.sql.ansi.enabled | true from Spark 4.0 | False up to 3.5. |
| trycast, trydivide | since Spark 3.2 | Column.trycast arrives in PySpark 4.0. |
| spark.python.worker.reuse | true | Python workers are reused between tasks. |
| spark.sql.execution.pythonUDF.arrow.enabled | off (added in 3.4) | A plain UDF then sends Arrow batches too. |
| spark.sql.execution.arrow.maxRecordsPerBatch | 10,000 | Rows in one Arrow batch. |
| .asNondeterministic() | UDFs are assumed deterministic | Mark a UDF that uses random numbers or the time, or Spark may call it more or fewer times than you expect. |
| spark.sql(..., args={...}) | Spark 3.4 and later | Parameters such as :s in SQL text. |
What changed at SwiftKart
The SQL rewrite was never merged. You replaced the UDF with built-ins: regexp_extract to read the product id, and a plain comparison on page for the filter. The plan has no BatchEvalPython line any more, the filter reaches the scan, and the job no longer reads all 4 TB.
The team kept both languages. Code reviews now flag any Python UDF that a built-in function could replace, and a cast that may meet bad text uses try_cast, with a count.
Next, Lesson 11.7: the interview version of today. You are handed a SQL query and asked to write it as DataFrame code, clause by clause.
In one line
SQL and DataFrame code become the same plan, so neither is faster; what slows a job is a Python UDF, and a built-in function usually replaces it.
Interview corner
Is Spark SQL faster than the DataFrame API?
No. Both are parsed into the same logical plan, optimized by Catalyst and executed as the same physical plan, so performance is identical. Choose by readability and testability: SQL for set logic people review, the API for reusable functions, loops over columns and unit tests.
Why are Python UDFs slow, and what do you use instead?
Spark executes on the JVM, so a Python UDF ships every row to a Python worker and back, and the optimizer cannot see inside it to push filters or simplify. Use built-in functions (when, regexp_extract, split, date functions), which run inside the engine. If you must run Python, a pandas UDF processes Arrow batches and is much faster than a row-at-a-time UDF.
What is the difference between a temp view and a table?
A temp view is a name for a DataFrame's plan inside one SparkSession: no data is stored, and it disappears when the session ends. A table (saveAsTable, or a Delta table in Unity Catalog) stores data and metadata in the catalog, survives sessions and can be shared and governed. Views are for composing a job; tables are for handing data to others.
What changes when a pipeline moves from Spark 3.5 to Spark 4.0 with default settings?
ANSI mode becomes the default (spark.sql.ansi.enabled=true), so operations that used to return null now raise errors: an invalid cast raises CAST_INVALID_INPUT, integer overflow ARITHMETIC_OVERFLOW instead of wrapping, division by zero DIVIDE_BY_ZERO, and an out-of-range array index INVALID_ARRAY_INDEX; type coercion is stricter too. Jobs that silently loaded nulls start failing on the same data. I would run the jobs on 4.0 in staging first, fix each failure on purpose with try_cast, try_divide or try_element_at plus a quarantine count, and keep ANSI on, because the errors are bad data that was always there.