Sub topic 15
Mixing SQL and DataFrames
This chapter assumes you can build a DataFrame, use F.col and built-in functions, and write basic SQL SELECT ... GROUP BY queries. You will learn to move between the two styles in one notebook.
Why mix the two
SQL and the DataFrame API compile to the same query plan. Neither is faster. Pick whichever reads better for the step at hand. SQL is often clearer for joins and aggregations. DataFrame code is easier to build up in pieces and to test.
Temporary views
A temporary view is a name for a DataFrame's query. It stores no data. You register it, and then SQL can refer to it by name.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
orders.createOrReplaceTempView("orders_v")
top = spark.sql("""
SELECT customer, SUM(amount) AS total_amount
FROM orders_v
GROUP BY customer
ORDER BY total_amount DESC
""")
display(top)createOrReplaceTempView replaces any existing view with the same name, so re-running the cell is safe. spark.sql returns a DataFrame. You can keep chaining DataFrame methods on it.
top.filter(F.col("total_amount") > 100).show()Moving in both directions
You can also write SQL directly in a cell that starts with the %sql magic command. Its result is displayed, but it is not assigned to a Python variable. Use spark.sql when you need the result in Python.
Scope and common errors
- A temporary view lives only in the current Spark session. Another notebook, even on the same cluster, cannot see it.
- Views are lazy. If you change
orderslater, the view still points at the old definition until you register it again. - A
Table or view not founderror usually means the cell that registers the view has not run, or the name is misspelled. - Do not build SQL by pasting untrusted text into the query string. Use
spark.sqlwith named parameters instead:
result = spark.sql(
"SELECT * FROM orders_v WHERE amount > :min_amount",
args={"min_amount": 50},
)
display(result)Parameter markers need a recent Databricks Runtime. If your runtime rejects them, check its version.
Exercise
You registered orders_v in notebook A. In notebook B, attached to the same cluster, spark.sql("SELECT * FROM orders_v") fails. Why, and what is one fix?
Show answer
Temporary views are scoped to a single Spark session, and each notebook has its own session, so notebook B cannot see the view. Fix it by registering the view again in notebook B from its own DataFrame, or by saving the data as a table with saveAsTable and reading that table from both notebooks.