Sub topic 15
Mixing SQL and DataFrames
This chapter assumes you can write basic Spark SQL and basic DataFrame code. It also assumes you know the preconfigured spark session and the difference between transformations and actions. Both interfaces use the same engine, so you can pick SQL or DataFrame code for each step of a notebook.
One engine, two front ends
A DataFrame expression and a SQL statement are both parsed into the same logical plan. Spark's optimizer then plans and runs them the same way. Choosing SQL over filter and groupBy does not change performance for equivalent queries. It only changes how the query is written.
spark.sql(...) returns a DataFrame, and any DataFrame can be exposed to SQL as a view. You can move between the two styles at any step.
Registering a temporary view
A temporary view is a name attached to a DataFrame's query plan. It stores no data and writes nothing to storage. When you query the view, Spark runs the plan behind it.
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",
).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 overwrites an existing view with the same name. createTempView raises an error if the name is already taken. In notebooks you re-run cells often, so the "replace" version is the usual choice.
Because the view holds a plan and not data, it reflects the DataFrame as it was when you registered it. If you later reassign the Python variable orders, the view still points at the old plan until you register again.
Going back from SQL to a DataFrame
There are three ways to get a DataFrame from SQL-side objects:
spark.sql("SELECT ...")runs any query and returns its result.spark.table("orders_v")returns the whole view or table as a DataFrame. It works for temporary views and for catalog tables.- In a
%sqlcell, recent Databricks runtimes expose the last result as a Python DataFrame named_sqldfin later Python cells.
Once you have a DataFrame, you can keep chaining DataFrame methods:
top_two = (
spark.table("orders_v")
.groupBy("customer")
.agg(F.sum("amount").alias("total_amount"))
.orderBy(F.col("total_amount").desc())
.limit(2)
)
top_two.show()Scope of a temporary view
A temporary view belongs to the Spark session. In a Databricks notebook, each attached notebook has its own session state. A view you create in one notebook is not visible in another notebook, even on the same cluster. It disappears when the notebook detaches or the cluster restarts.
| Kind | Created with | Visible to | Lifetime |
|---|---|---|---|
| Temporary view | `createOrReplaceTempView("v")` | The creating notebook's session | Until the session ends |
| Global temporary view | `createOrReplaceGlobalTempView("v")` | Sessions on the same Spark application, as `global_temp.v` | Until the application ends |
| Table | `saveAsTable("catalog.schema.t")` | Anyone with permission | Until dropped |
Use a global temporary view rarely. If another notebook or a job needs the data, write a table instead. A table has permissions and a stable name, and it does not depend on a running cluster.
orders.createOrReplaceGlobalTempView("orders_g")
spark.sql("SELECT COUNT(*) AS n FROM global_temp.orders_g").show()SQL cells with the %sql magic
A notebook whose default language is Python can still run SQL in a cell that starts with %sql. The cell can query temporary views and catalog tables directly.
%sql
SELECT customer, COUNT(*) AS order_count
FROM orders_v
GROUP BY customer
ORDER BY order_count DESCA %sql cell shows its result as a table, and in recent runtimes the result is also available as _sqldf. The magic switches the language of that one cell. Python variables are not visible inside it, so you cannot write {some_var} in the SQL text and expect substitution. For that, use spark.sql from a Python cell.
Passing values into spark.sql safely
It is tempting to build queries with f-strings:
min_amount = 50
spark.sql(f"SELECT * FROM orders_v WHERE amount > {min_amount}").show()This works for a number you control. If the value comes from a widget, a file, or a user, the f-string lets that text become part of the SQL. In Spark 3.4 and later, named parameters avoid the problem:
spark.sql(
"SELECT * FROM orders_v WHERE amount > :min_amount AND customer = :who",
args={"min_amount": 50, "who": "alice"},
).show()Parameters substitute values only. They cannot substitute table or column names. If you need a dynamic table name, validate it against a known list before building the string.
Choosing between SQL and DataFrame code
Neither style is faster. Choose by readability and by what the step needs:
- Use SQL for multi-way joins,
CASEexpressions, CTEs, and window definitions that read naturally as one statement. - Use DataFrame code when the logic is built in a loop, when column lists come from variables, or when you want to reuse a transformation as a Python function.
- Use temporary views as the seam between them. Name a view after the step it represents, such as
orders_clean_v, so later cells read well.
A mixed pipeline is a common pattern. A Python cell cleans the data, a view exposes it, and a SQL cell does the business logic:
clean = (
orders
.dropDuplicates(["order_id"])
.filter(F.col("amount").isNotNull())
)
clean.createOrReplaceTempView("orders_clean_v")
monthly = spark.sql("""
WITH m AS (
SELECT date_trunc('month', order_date) AS month, amount
FROM orders_clean_v
)
SELECT month, SUM(amount) AS revenue
FROM m
GROUP BY month
ORDER BY month
""")
display(monthly)Common errors
TABLE_OR_VIEW_NOT_FOUND: The view was created in another notebook, the cluster restarted, or the name is misspelled. Re-run the cell that registers it.TEMP_TABLE_OR_VIEW_ALREADY_EXISTS: You usedcreateTempViewtwice. Switch tocreateOrReplaceTempView.- Stale results: You changed a DataFrame variable but did not re-register the view.
- Confusing a view with a cache: A view does not store results, so each query recomputes the plan. If many queries reuse an expensive result, cache the DataFrame or write a table.
Exercise
A colleague creates orders.createOrReplaceTempView("orders_v") in notebook A. In notebook B, attached to the same cluster, spark.sql("SELECT * FROM orders_v") fails. Why does it fail, and name two ways to make the data available in notebook B.
Show answer
Temporary views are scoped to the notebook's Spark session, so notebook B cannot see the view from notebook A. You can register a global temporary view in notebook A and query it as global_temp.orders_v in notebook B, which only works while the Spark application runs. The better option is to save the DataFrame with saveAsTable("catalog.schema.orders") and read it in notebook B with spark.table, because tables persist and have permissions.