spark.sql and temp views
Some steps read better in SQL, others in DataFrame code. Spark lets you mix them freely: give a DataFrame a name, query it with SQL, and keep working on the result. This lesson shows how, the kinds of views and how long they live, and how to pass values into SQL safely.
Step 1 · PySpark functions · Bronze · Combine and summarise, lesson 4 of 4
On this page
Show code in
Every code block on the page follows this.
Read first: select (skip if you know it)
In plain words first
A view is a name tag on a DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more →. Pin the tag "orders" on it, and SQL can now say FROM orders. The tag does not copy the data or save it anywhere; it only lets SQL find the DataFrame by name for as long as your session lasts.
Going back and forth
orders.createOrReplaceTempView("orders") top = spark.sql(""" SELECT customer, SUM(amount) AS total FROM orders GROUP BY customer """) result = top.filter(F.col("total") > 1000).orderBy(F.desc("total"))
The result of spark.sql is an ordinary DataFrame: you can keep chaining DataFrame methods, register it as another view, or write it out. Nothing runs until an action, exactly as with DataFrame code.
Views and tables
| Kind | Created with | Visible to | Lives until |
|---|---|---|---|
| Temp view | createOrReplaceTempView | This Spark session only | The session ends |
| Global temp view | createOrReplaceGlobalTempView; query as global_temp.name | All sessions in the same application | The application ends |
| Table | saveAsTable, CREATE TABLE | Everyone using the catalog | Dropped |
| Permanent view | CREATE VIEW in SQL | Everyone using the catalog | Dropped; stores only the query, not data |
A temp view stores no data. It is a name for a plan: querying it re-runs the plan, including reading the source, unless the DataFrame is cached.
Passing parameters safely
Building SQL with f-strings breaks on quotes in values and opens the door to SQL injection when values come from users or files. Spark 3.4+ supports named parameters:
# Fragile: breaks for O'Brien, and unsafe with untrusted input spark.sql(f"SELECT * FROM orders WHERE customer = '{name}'") # Safe: the value is passed separately spark.sql("SELECT * FROM orders WHERE customer = :name AND amount > :min", args={"name": name, "min": 100}) # DataFrames can be passed straight in (Spark 3.4+) spark.sql("SELECT * FROM {o} WHERE amount > 100", o=orders)
Same plan, same speed
SQL text and DataFrame calls are two front ends to the same engine. Both are parsed into a logical plan, optimised by CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → and executed the same way. explain() on either shows identical physical plans for equivalent queries. Choose by readability: SQL for analysts and long set-based logic, DataFrames when you build queries dynamically in Python (loops over columns, reusable functions, unit tests).
SQL · text
The command
spark.sql(""" SELECT customer, SUM(amount) AS revenue FROM orders WHERE amount > 0 GROUP BY customer """)
SELECT customer, SUM(amount) AS revenue FROM orders WHERE amount > 0 GROUP BY customer
DataFrame · calls
The command
orders.filter("amount > 0").groupBy("customer").agg(F.sum("amount").alias("revenue"))
Catalyst · optimise
Mixing them well
F.expr("CASE WHEN ... END")anddf.selectExpr("amount * 1.18 AS gross")embed SQL expressions inside DataFrame code.df.filter("amount > 100")accepts a SQL condition string.- Register intermediate results as views to break a long SQL pipeline into readable steps, or use CTEs (
WITH ... AS) inside one query. - Use
spark.table("db.orders")to read a catalog table as a DataFrame.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Query a DataFrame with SQL through a temp view, and pass values safely as named parameters.
orders = spark.createDataFrame( [(1, "IN", 120.0), (2, "US", 80.0), (3, "IN", 45.0)], ["id", "country", "amount"]) orders.createOrReplaceTempView("orders") def revenue_for(country): # Named parameters (Spark 3.4+): the value is never pasted into the SQL text. return spark.sql(""" SELECT country, SUM(amount) AS revenue FROM orders WHERE country = :country GROUP BY country""", args={"country": country}) revenue_for("IN").show() attack = "IN' OR '1'='1" print("rows with a parameter:", spark.sql( "SELECT * FROM orders WHERE country = :c", args={"c": attack}).count()) print("rows with an f-string:", spark.sql( f"SELECT * FROM orders WHERE country = '{attack}'").count())
Output from a real run
+-------+-------+ |country|revenue| +-------+-------+ | IN| 165.0| +-------+-------+ rows with a parameter: 0 rows with an f-string: 3
What to notice:
- India's revenue is 165.0: orders 1 and 3 (120 + 45).
- The malicious value returned 0 rows as a parameter: Spark looked for a country literally called
IN' OR '1'='1. - Pasted into an f-string, the same value returned all 3 rows: it rewrote the query. Table and column names cannot be parameters, so check those against an allow-list.
Common mistakes
- f-strings for values — Breaks on quotes and is open to injection. Use args or the DataFrame API.
- Expecting a temp view to be visible in another notebook or job — Temp views live in one session. Write a table to share data.
- Believing SQL is faster (or slower) than DataFrames — Both compile to the same plan.
- Treating a view as cached — A view re-runs its plan every time it is queried.
Key takeaways
- createOrReplaceTempView names a DataFrame for SQL in one session.
- spark.sql returns a lazy DataFrame.
- Pass values with args, never with f-strings.
- SQL and DataFrames compile to the same plan and run at the same speed.
Interview prep
THE QUESTION
"Is Spark SQL faster than the DataFrame API?"
explain() shows. The choice is about readability, testability and how dynamic the query is. The one real performance difference is Python UDFs, which cost the same from either API.Avoid: "SQL is faster" or "DataFrames are faster". Both compile to the same plan.
Follow-ups · answer out loud, then open
Follow-up"Temp view vs global temp view: what is the difference?"
global_temp database and is visible to all sessions of the same application. Neither stores data; they are named query plans.Scenario"A user-provided date goes into spark.sql with an f-string. What is wrong, and what do you use instead?"
spark.sql("SELECT * FROM t WHERE d = :d", args={"d": day}) (Spark 3.4+). Table and column names cannot be parameters; validate them against an allow-list.Trap"createOrReplaceTempView caches the DataFrame."
Check yourself
3 questionsWhere is a temp view visible?
Show the answer
Only in the session that created it. Temp views are session-scoped; global temp views are application-scoped.
Does a temp view store data?
Show the answer
No, it names a plan that is re-run when queried. A view is a name for a query plan; cache the DataFrame if you need it kept.
Which is the safe way to filter by a user-supplied name?
Show the answer
spark.sql with args={"name": name}. Parameters are passed separately from the SQL text, so quotes cannot break or inject into the query.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Window functions · 4 min readrow_number / rank
Number and rank rows inside a window, and how the three ranking functions treat ties.
Related lessons
Catalyst and physical plansPySpark functions · 6 min read
selectSpark internals · 5 min read
SQL pipe syntax
Previous: join
Primary sources: SparkSession.sql · DataFrame.createOrReplaceTempView