CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 2 · Lesson 11/32

    Temporary views in Spark SQL: createOrReplaceTempView and global_temp

    Register DataFrames as temporary views in Spark SQL, allowing them to be queried with SQL syntax.

    14 min read
    5% of exam
    12 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Registering a DataFrame as the local view people and querying it with SQLpython
    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|
    # +---+-----+

    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?

    Sources123456

    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.

    The four DataFrame methods that register a temporary view
    MethodScopeIf the name already exists
    createTempView(name)Local: tied to the SparkSessionThrows TempTableAlreadyExistsException
    createOrReplaceTempView(name)Local: tied to the SparkSessionReplaces the existing view
    createGlobalTempView(name)Global: tied to the Spark applicationThrows TempTableAlreadyExistsException
    createOrReplaceGlobalTempView(name)Global: tied to the Spark applicationReplaces 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.

    createOrReplaceTempView pointing the name people at a filtered DataFramepython
    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?

    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?

    Sources627

    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.

    A global temporary view, queried through the global_temp schemapython
    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?

    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?

    Sources387910

    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.

    Dropping a local view, after which the name no longer resolvespython
    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.

    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")
    # True

    Sources1141215

    Sources

    (12)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 2.
      “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. 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. 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. 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. 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. 7.
      “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. 8.
      “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. 9.
      “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. 10.
      “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. 11.
      “Returns true if this view is dropped successfully, false otherwise.”
      ↩︎ Dropping and listing temporary views

    Spotted a mistake, or was something unclear? Tell us.