What you will be able to do
- Register a DataFrame as a temporary view and query it with spark.sql or spark.table
- Predict whether createTempView, createOrReplaceTempView, createGlobalTempView or createOrReplaceGlobalTempView fails or replaces when a view name already exists
- Choose between a session-scoped view and a global temporary view, and qualify global views with global_temp
- Drop temporary views through spark.catalog and recognise the error that a dropped or invisible view produces
Key concept
Temporary view — A name registered in the catalog that points at a DataFrame, so that SQL can query the DataFrame as if it were a table. It stores no data of its own and disappears with the scope it was created in: the SparkSession for a local view, or the Spark application for a global one.
1.Giving a DataFrame a name that SQL can see
Spark SQL can't see a DataFrame that only exists as a Python variable until you register a name for it in the catalog. spark.sql() takes a query string and returns a DataFrame. The table names inside that string are looked up as catalog names. Say you build a variable called sales_df and then run SELECT * FROM sales_df. The query fails unless something has registered the name sales_df first.
A temporary view is that registration. Calling df.createOrReplaceTempView("people") binds the name people to the DataFrame, and from then on spark.sql("SELECT * FROM people") works. A view is a virtual table. It holds no physical data, only the definition it was built from, so registering one reads nothing and writes nothing. The DataFrame API can use the same name: spark.table("table1") returns a registered view as a DataFrame, and that is how two registered views can be combined with union.
df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
df.createTempView("people")
spark.sql("SELECT * FROM people").show()
# +---+-----+
# |age| name|
# +---+-----+
# | 2|Alice|
# | 5| Bob|
# +---+-----+Several other calls sound as if they do the same job, but none of them registers a name for SQL. df.write.saveAsTable(...) writes the data out as a persistent table, which outlives the session and costs a full write. spark.catalog.cacheTable(name) caches a table that already exists in the catalog, using MEMORY_AND_DISK by default. It needs a name that already exists and doesn't create one. df.persist(...) sets a storage level on the DataFrame but gives SQL no name to refer to. The DataFrame class has four methods that register a view: createTempView, createOrReplaceTempView, createGlobalTempView and createOrReplaceGlobalTempView. To run ad-hoc SQL against a DataFrame in the same notebook, use createOrReplaceTempView.
Checkpoint 1 of 7· Fill the gap
This sample registers the DataFrame df so that the spark.sql() query on the next line can find the name people. Which method completes it?
df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
df. ? ("people")
spark.sql("SELECT * FROM people").show()
# +---+-----+
# |age| name|
# +---+-----+
# | 2|Alice|
# | 5| Bob|
# +---+-----+createTempView is one of the four DataFrame methods that register a view name in the catalog, so spark.sql can then resolve people. cacheTable is a spark.catalog method and needs a name that already exists. persist only sets a storage level and gives SQL no name. saveAsTempTable is not a DataFrame method.
Checkpoint 2 of 7· Exam question
A data engineer builds a PySpark DataFrame sales_df from a CSV file and needs to run ad-hoc SQL aggregations against it using spark.sql() within the same notebook session. Which line of code registers sales_df so it can be queried by name in Spark SQL?
Correct answer: A — sales_df.createOrReplaceTempView("sales_df")
- A. This call registers the DataFrame as a session-scoped temporary view so
spark.sql()can resolvesales_dfby name in a query. It is the current, non-deprecated API for exactly this purpose. - B. This writes the DataFrame out as a persistent metastore table, which is a heavier operation that durably stores data on disk rather than simply registering a name for ad-hoc SQL access.
- C.
cacheTablemarks an already-registered table or view for in-memory caching; it does not register a DataFrame as a queryable name, so calling it here without a prior registration would fail. - D.
registerTempTablewas the 1.x-era API for this purpose and has been removed from current Spark releases, so relying on it will raise anAttributeErroron a modern cluster. - E.
persistcontrols the storage level used when the DataFrame is later computed, but it does not give Spark SQL a name to resolve, sospark.sql()still could not findsales_df.
2.What happens when the view name already exists
The four registration methods differ in two ways: whether the view is local or global, and what happens when the name is already taken. The second difference is the one that breaks notebooks, and simply re-running a cell is enough to trigger it.
| Method | Scope | If the name already exists |
|---|---|---|
| createTempView(name) | Local: tied to the SparkSession | Throws TempTableAlreadyExistsException |
| createOrReplaceTempView(name) | Local: tied to the SparkSession | Replaces the existing view |
| createGlobalTempView(name) | Global: tied to the Spark application | Throws TempTableAlreadyExistsException |
| createOrReplaceGlobalTempView(name) | Global: tied to the Spark application | Replaces the existing view |
createTempView refuses to overwrite. A second call with the same name raises AnalysisException: "Temporary table 'people' already exists;", and the original view is left unchanged. That strictness helps in a pipeline where two steps must never claim the same name by accident. In an interactive notebook, where you re-run cells all the time, it gets in the way.
createOrReplaceTempView points the existing name at the new DataFrame instead. After the second call the name refers only to the new DataFrame. The old binding is gone, the two DataFrames' rows are not combined, and no versions are kept. In the example below, people ends up meaning the filtered df2, so a query against people returns exactly what df2 holds. The same applies if you register spark.range(5) and then spark.range(5, 10) under one name: COUNT(*) against that name returns 5, the size of the second range. It doesn't return 10, and it doesn't raise an error.
df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
df.createOrReplaceTempView("people")
df2 = df.filter(df.age > 3)
df2.createOrReplaceTempView("people")
df3 = spark.sql("SELECT * FROM people")
assert sorted(df3.collect()) == sorted(df2.collect())Checkpoint 3 of 7· Check yourself
A long-running Spark application calls df.createGlobalTempView("daily") once per batch. The first batch works. What happens on the second batch, and what change fixes it?
Like createTempView, createGlobalTempView throws TempTableAlreadyExistsException when the name already exists. Only the OrReplace variants overwrite, and the global variant is createOrReplaceGlobalTempView. createOrReplaceTempView would create a local view instead.
“The lifetime of this temporary view is tied to this Spark application. throws TempTableAlreadyExistsException, if the view name already exists in the catalog.”Source: docs.databricks.com
Checkpoint 4 of 7· Exam question
A notebook runs the following code in a single Spark session:
df1 = spark.range(5)
df1.createOrReplaceTempView("nums")
df2 = spark.range(5, 10)
df2.createOrReplaceTempView("nums")
result = spark.sql("SELECT COUNT(*) AS cnt FROM nums")
What does result contain after this code runs?
Correct answer: A — A single row with cnt equal to 5, because the second createOrReplaceTempView call overwrote the temporary view named nums with df2.
- A.
createOrReplaceTempViewoverwrites any existing view of the same name in the current session, so after the second callnumsrefers only todf2, which has 5 rows (5 through 9). - B. Reusing a temporary view name does not union the prior and new DataFrames; the earlier binding is discarded entirely, so no union ever happens.
- C. Raising an exception on reuse is the behavior of
createTempView, notcreateOrReplaceTempView, which is designed specifically to replace an existing view without error. - D. Replacing a temporary view does not clear or null out the referenced data; the view simply points at whichever DataFrame was registered most recently, which still has 5 rows.
- E. Spark SQL does not version temporary view registrations; a name can be bound to only one DataFrame at a time, so no combined two-row result is produced.
3.Session-scoped views and global temporary views
A local temporary view belongs to one SparkSession and ends with it. Only the session that created the view can see it, and the view is dropped when that session ends (see SparkSession lifecycle). No other session can resolve the name, even one running on the same cluster at the same time.
On Databricks this limit falls at the notebook boundary. Temporary views created in a notebook or job are scoped to that notebook or script. Another notebook can't reference them, and they stop existing when the notebook detaches from the cluster. Suppose a colleague attaches a second notebook to your shared cluster and queries your orders_view. They get a table-or-view-not-found error. The data, the name and the runtime are all fine. Their notebook simply runs in a different session from the one that registered the view.
A global temporary view lasts as long as the Spark application rather than the session, and it lives in a system-preserved schema called global_temp. Every query has to name that schema, for example SELECT * FROM global_temp.people or spark.table("global_temp.people"). The bare name people doesn't find the global view. Because the view belongs to the application, other sessions can query it too: views in the global_temp schema are visible to all users sharing the cluster.
df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
df.createGlobalTempView("people")
df2 = spark.sql("SELECT * FROM global_temp.people")
df2.show()
# +---+-----+
# |age| name|
# +---+-----+
# | 2|Alice|
# | 5| Bob|
# +---+-----+Use a local view by default. It goes away with its session, and it is all a single notebook needs. Use a global view only when separate sessions on one cluster really do need to share a registered DataFrame, and remember that everyone on that cluster can then query it. Databricks serverless compute doesn't support global temporary views, and Databricks recommends session-scoped views there instead.
Checkpoint 5 of 7· Check yourself
Your colleague attaches a second notebook to your shared classic cluster and needs to query the DataFrame you have registered as orders. Which combination of registration and query works?
A local view belongs to the notebook's session, so another notebook can't resolve it. A global view lasts as long as the application and lives in the global_temp schema, so every query has to include that prefix.
“df.createGlobalTempView("people") df2 = spark.sql("SELECT * FROM global_temp.people")”Source: docs.databricks.com
Checkpoint 6 of 7· Exam question
A data engineer registers a temporary view in Notebook A on a shared interactive cluster: orders_df.createOrReplaceTempView("orders_view"). A colleague opens Notebook B, attaches it to the same cluster, and runs spark.sql("SELECT * FROM orders_view"), receiving Table or view not found: orders_view. What is the most likely cause?
Correct answer: A — orders_view was registered as a session-scoped temporary view, and Notebook B runs in a separate SparkSession that cannot see it.
- A.
createOrReplaceTempViewscopes the view to theSparkSessionthat created it. Each notebook attached to a cluster typically runs its own session, so a session-scoped view registered in one notebook is invisible to another. - B. Registering a temporary view does not trigger a write to storage at all; the view is a name bound to an in-memory DataFrame lineage, so write timing is not the cause of a not-found error.
- C. Unity Catalog governs permanent catalog objects and does not control the visibility of session-scoped temporary views, so its absence is not what produces this error.
- D.
orders_viewis not a reserved Spark SQL keyword, and keyword collisions produce a parse error rather than a table-or-view-not-found error. - E. Temporary view visibility depends on the
SparkSessionthat created it, not on the Databricks Runtime version, so a runtime mismatch would not explain this specific error.
4.Dropping and listing temporary views
You drop temporary views through the catalog API, which has one method for each scope. spark.catalog.dropTempView(name) removes a local view and spark.catalog.dropGlobalTempView(name) removes a global one. The global method takes the bare view name, as in dropGlobalTempView("my_table"), without the global_temp. prefix. Both methods return True if the view was dropped and False otherwise. If the view had been cached, dropping it also removes it from the cache.
spark.createDataFrame([(1, 1)]).createTempView("my_table")
# Dropping the temporary view.
spark.catalog.dropTempView("my_table")
# True
# Throw an exception if the temporary view does not exist.
spark.table("my_table")
# Traceback (most recent call last):
# ...
# AnalysisException: ...Dropping a view is also how you get past the createTempView name clash: drop the name, then create the view again. To see what is registered, call spark.catalog.listTables(). It returns the tables and views in a database, including every temporary view, so a view you have just created shows up in its output.
A query that has already returned can still fail later if Spark has not yet looked up the view name when you drop or replace the view. Whether it has depends on the mode PySpark runs in, Spark Classic or Spark Connect. In Spark Classic, a view referenced in spark.sql is resolved immediately, at the moment of the call, so the name is bound before spark.sql returns. In Spark Connect, analysis is lazy: the lookup of the view is deferred rather than done at the call. Suppose you run df = spark.sql("SELECT * FROM people"), then re-register people with a filtered DataFrame, then call df.show(). Under Spark Connect, the query can fail or return different rows, because the view is no longer the one that existed when you wrote the query. Under Spark Connect, finish using a query's result before you drop or re-register the views it reads.
It raises an AnalysisException. Once the global view is dropped it no longer exists in global_temp, and reading a view that doesn't exist throws an exception. It does not return an empty DataFrame.
Checkpoint 7 of 7· Fill the gap
The code below rebinds a global view and reads it back through global_temp. Which catalog method in the last call removes that view?
df = spark.createDataFrame([(2, "Alice"), (5, "Bob")], schema=["age", "name"])
df.createOrReplaceGlobalTempView("people")
df2 = df.filter(df.age > 3)
df2.createOrReplaceGlobalTempView("people")
df3 = spark.table("global_temp.people")
sorted(df3.collect()) == sorted(df2.collect())
# True
spark.catalog. ? ("people")
# TrueThe catalog API has one drop method for each scope, and a global view is removed with dropGlobalTempView. It takes the bare name without the global_temp. prefix and returns True. dropTempView removes local views only, uncacheTable takes a view out of the cache but leaves it registered, and the lesson names no dropView method on spark.catalog.
Source: docs.databricks.comSources
(12)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Returns a DataFrame representing the result of the given query.”
↩︎ Giving a DataFrame a name that SQL can see“In Spark Classic, a temporary view referenced in spark.sql is resolved immediately.”
↩︎ Dropping and listing temporary views“if a view is dropped, modified, or replaced after spark.sql, the execution may fail or generate different results.”
↩︎ Dropping and listing temporary views - 2.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/createOrReplaceTempViewOfficial docs
“Creates or replaces a local temporary view with this DataFrame.”
↩︎ Giving a DataFrame a name that SQL can see“Creates or replaces a local temporary view with this DataFrame.”
↩︎ What happens when the view name already exists“The lifetime of this temporary table is tied to the SparkSession that was used to create this DataFrame.”
↩︎ Key concept - 3.
“Constructs a virtual table that has no physical data based on the result-set of a SQL query”
↩︎ Giving a DataFrame a name that SQL can see“TEMPORARY views are visible only to the session that created them and are dropped when the session ends.”
↩︎ Session-scoped views and global temporary views“GLOBAL TEMPORARY views are tied to a system preserved temporary schema global_temp.”
↩︎ Session-scoped views and global temporary views“GLOBAL TEMPORARY views are tied to a system preserved temporary schema global_temp.”
↩︎ Exam trap 3 - 4.
“Caches the specified table in-memory or with the given storage level. Defaults to MEMORY_AND_DISK.”
↩︎ Giving a DataFrame a name that SQL can see“Drops the global temporary view with the given name. Also uncaches the view if it was cached.”
↩︎ Dropping and listing temporary views“Returns a list of tables and views in the specified database. Includes all temporary views.”
↩︎ Dropping and listing temporary views“Caches the specified table in-memory or with the given storage level. Defaults to MEMORY_AND_DISK.”
↩︎ Exam trap 4 - 5.
“createGlobalTempView(name) | Creates a global temporary view with this DataFrame.”
↩︎ Giving a DataFrame a name that SQL can see“Returns the content as an RDD of Row (Classic mode only).”
↩︎ Dropping and listing temporary views - 6.
“result_df = spark.table("table1").union(spark.table("table2"))”
↩︎ Giving a DataFrame a name that SQL can see“throws TempTableAlreadyExistsException, if the view name already exists in the catalog.”
↩︎ What happens when the view name already exists“AnalysisException: "Temporary table 'people' already exists;"”
↩︎ What happens when the view name already exists“throws TempTableAlreadyExistsException, if the view name already exists in the catalog.”
↩︎ Exam trap 1 - 7.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/createGlobalTempViewOfficial docs
“The lifetime of this temporary view is tied to this Spark application.”
↩︎ What happens when the view name already exists“The lifetime of this temporary view is tied to this Spark application.”
↩︎ Session-scoped views and global temporary views“The lifetime of this temporary view is tied to this Spark application. throws TempTableAlreadyExistsException, if the view name already exists in the catalog.”
↩︎ Checkpoint“df.createGlobalTempView("people") df2 = spark.sql("SELECT * FROM global_temp.people")”
↩︎ Checkpoint - 8.https://docs.databricks.com/aws/en/viewsOfficial docs
“In notebooks and jobs, temporary views are scoped to the notebook or script level.”
↩︎ Session-scoped views and global temporary views“They cannot be referenced outside of the notebook in which they are declared, and no longer exist when the notebook detaches from the cluster.”
↩︎ Exam trap 2 - 9.https://docs.databricks.com/aws/en/data-governance/unity-catalog/access-control/table-acls/object-privilegesOfficial docs
“views created in the global_temp schema are visible to all users sharing a cluster or SQL warehouse”
↩︎ Session-scoped views and global temporary views - 10.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/createOrReplaceGlobalTempViewOfficial docs
“Databricks recommends using session-scoped temp views (createOrReplaceTempView) on serverless compute, since global_temp views are not supported.”
↩︎ Session-scoped views and global temporary views - 11.
“Returns true if this view is dropped successfully, false otherwise.”
↩︎ Dropping and listing temporary views - 12.https://docs.databricks.com/aws/en/pyspark/reference/classes/catalog/dropGlobalTempViewOfficial docs
“spark.catalog.dropGlobalTempView("my_table")”
↩︎ Dropping and listing temporary views