Skip to content
Bronze 6 min read · SQL 2 practice problems ↓

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

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

PySpark · DataFrame → SQL → DataFrame
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

KindCreated withVisible toLives until
Temp viewcreateOrReplaceTempViewThis Spark session onlyThe session ends
Global temp viewcreateOrReplaceGlobalTempView; query as global_temp.nameAll sessions in the same applicationThe application ends
TablesaveAsTable, CREATE TABLEEveryone using the catalogDropped
Permanent viewCREATE VIEW in SQLEveryone using the catalogDropped; 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:

PySpark · Parameters, not string formatting
# 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

Spark parses the string into an unresolved plan.

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

Each method call adds a node to the same kind of plan.

The command

orders.filter("amount > 0").groupBy("customer").agg(F.sum("amount").alias("revenue"))

Catalyst · optimise

Both are resolved against the catalog, optimised (filters pushed down, columns pruned) and turned into the same physical plan. From here on there is no difference.

Mixing them well

  • F.expr("CASE WHEN ... END") and df.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.

Production patternPySpark · Temp views and parameterised SQL in a job
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?"

No: both produce the same logical plan, Catalyst optimises it the same way and the physical plans match, which 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?"
A temp view lives in one SparkSession and disappears with it. A global temp view lives in the 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?"
Formatting values into SQL text invites SQL injection and quoting bugs. Use parameters: 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."
No. A view is just a name for the plan. Querying it recomputes from the source unless you cache explicitly.

Check yourself

3 questions

Where 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 read
row_number / rank
Number and rank rows inside a window, and how the three ranking functions treat ties.

Related lessons

Previous: join

Primary sources: SparkSession.sql · DataFrame.createOrReplaceTempView