SQL on DataFrames
clean.createOrReplaceTempView("orders")
customers.createOrReplaceTempView("customers")
spark.sql("""
SELECT c.city,
COUNT(*) AS orders,
ROUND(SUM(o.amount), 0) AS revenue
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_status = 'DELIVERED'
GROUP BY c.city
ORDER BY revenue DESC
""").show()+---------+------+-------+
| city|orders|revenue|
+---------+------+-------+
| Delhi| 954|2200709|
|Bengaluru| 889|2087701|
| Mumbai| 832|1897466|
| Kolkata| 775|1780712|
| Pune| 695|1610135|
+---------+------+-------+Same numbers as the Snowflake course's first report, now from PySpark. A temp view is just a name for a DataFrame; nothing is copied.
top_city = spark.sql("SELECT city FROM customers GROUP BY city ORDER BY COUNT(*) DESC LIMIT 1")
print(top_city.first()["city"])
print(spark.sql("SELECT COUNT(*) AS n FROM orders WHERE is_big").first()["n"], "big orders")Delhi
274 big ordersspark.sql(...) returns a normal DataFrame, so you can switch between SQL and Python at any step. Teams often write transformations in SQL and orchestration in Python.
UDFs: Python on every row
Suppose we want price bands (budget / mid / premium). Here are three ways, timed on about a million rows (our orders cross-joined 200 times and cached, on an 8-core laptop):
from pyspark.sql.types import StringType
import time
@F.udf(returnType=StringType())
def price_band(price):
if price is None:
return None
return "budget" if price < 1000 else ("mid" if price < 3000 else "premium")
builtin_band = (F.when(F.col("unit_price") < 1000, "budget")
.when(F.col("unit_price") < 3000, "mid")
.otherwise("premium"))
big = clean.crossJoin(spark.range(200)).cache() # ~1 million rows to make timing visible
print(big.count(), "rows")
for name, expr in [("python udf", price_band("unit_price")), ("built-in when", builtin_band)]:
start = time.time()
big.groupBy(expr.alias("band")).count().collect()
print(f"{name:<14} {time.time() - start:.2f} s")1063000 rows
python udf 1.32 s
built-in when 0.27 sfrom pyspark.sql.functions import pandas_udf
import pandas as pd
@pandas_udf("string")
def price_band_vec(price: pd.Series) -> pd.Series:
return pd.cut(price.astype(float), [0, 1000, 3000, float("inf")],
right=False, labels=["budget", "mid", "premium"]).astype(str)
start = time.time()
big.groupBy(price_band_vec("unit_price").alias("band")).count().orderBy("band").show()
print(f"pandas udf {time.time() - start:.2f} s")+-------+------+
| band| count|
+-------+------+
| budget|359400|
| mid|526800|
|premium|176800|
+-------+------+
pandas udf 1.56 s| Approach | Time (our run) | Why |
|---|---|---|
| Built-in when / otherwise | 0.27 s | Runs in the JVM with code generation; optimizer understands it |
| Python UDF (@udf) | 1.32 s | Every row goes JVM → Python → JVM |
| pandas UDF (@pandas_udf) | 1.34 s (includes sorting and printing) | Batches via Arrow; vectorized pandas code |
The built-in version was about 5× faster than the Python UDF. On a laptop with a simple function the pandas UDF roughly matched the plain UDF (its timing also includes ordering and show()); with heavier Python logic and bigger data, vectorized pandas UDFs usually pull well ahead of row-by-row UDFs. Timings vary run to run; the ranking is what matters.
What's next in this course
You can now read, clean, join, rank and query data with PySpark. The next lessons (coming soon) cover performance tuning (partitions, caching, AQE, skew), Delta Lake and Structured Streaming, testing PySpark with pytest, and interview questions.
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1How do you run SQL in PySpark?Fresher+
Q2Why are Python UDFs slow, and what are the alternatives?1–3 yrs+
Q3Temp view vs global temp view vs table?1–3 yrs+
Q4A pipeline uses many Python UDFs and is slow. How do you speed it up?3+ yrs+
Key takeaways
- ✓SQL or DataFrames: same engine, pick what's clearest.
- ✓Built-ins were 5× faster than a Python UDF in our test.
- ✓Use pandas UDFs when you really need Python at scale.
- ✓Next: performance, Delta, streaming and testing.
Frequently asked questions
Is Spark SQL slower than the DataFrame API?
No. Both compile to the same optimized plan (Catalyst), so they run at the same speed. Choose whichever is clearer for the task, and mix them freely.
What's a temp view?
A name for a DataFrame that SQL can query, valid for the current SparkSession: df.createOrReplaceTempView('orders'). A global temp view is shared across sessions in the same application; a table (saveAsTable) is stored in a catalog.
Why are Python UDFs slow?
Each row is serialized from the JVM to a Python worker and back, and Spark's optimizer can't see inside your function. Built-in functions run inside the JVM with code generation.
When should I use a pandas UDF?
When you truly need Python (a library, complex logic) on large data. pandas UDFs move data in batches with Apache Arrow and work on whole pandas Series, which is usually much faster than row-at-a-time UDFs.
🧠 Quick check: Spark SQL and UDFs
1. Which was fastest for the price bands on a million rows?
2. How do you query a DataFrame with SQL?
3. Spark SQL vs DataFrame API performance?
4. Best first choice for custom logic?
Checking your access…