๐Ÿ—‚๏ธ Tables & Views

Before you can query data with SQL, Spark needs to know it by name. In this tutorial you will learn the four kinds of named objects in Spark (temporary views, global temporary views, managed tables and external tables), how to create and fill them, and which one to use when.


1. Sample Data

The examples use a small orders view. Run this first:

CREATE OR REPLACE TEMP VIEW orders AS
SELECT * FROM VALUES
  (101, 'Asha',  DATE'2024-01-05', 'Electronics', 250),
  (102, 'Ben',   DATE'2024-01-05', 'Books',        40),
  (103, 'Asha',  DATE'2024-01-06', 'Books',        25),
  (104, 'Chen',  DATE'2024-01-06', 'Electronics', 520),
  (105, 'Divya', DATE'2024-01-07', 'Home',        130),
  (106, 'Ben',   DATE'2024-01-07', 'Electronics',  75)
AS orders(order_id, customer, order_date, category, amount)

2. Tables vs Views: The Big Picture

The difference comes down to one question: is data stored?

  • A table points to data files (Parquet, Delta, CSV and so on) that live on disk or in cloud storage.
  • A view stores no data. It is a saved query that runs every time you select from it.

Spark gives you four options:

ObjectStores data?Lives untilVisible toDROP deletes the files?
Temporary viewNoYour Spark session endsYour session onlyNothing to delete
Global temporary viewNoThe Spark application stopsAll sessions in the applicationNothing to delete
Managed tableYes, in Spark's warehouse folderYou drop itEveryone using the catalogYes
External tableYes, at a location you chooseYou drop itEveryone using the catalogNo

The rest of this tutorial walks through each one.


3. Temporary Views

You already created one: orders. A temp view is the everyday tool for giving a query a name, so later queries can build on it:

CREATE OR REPLACE TEMP VIEW big_orders AS
SELECT order_id, customer, amount
FROM orders
WHERE amount > 100
SELECT * FROM big_orders ORDER BY order_id
+--------+--------+------+
|order_id|customer|amount|
+--------+--------+------+
|101     |Asha    |250   |
|104     |Chen    |520   |
|105     |Divya   |130   |
+--------+--------+------+

big_orders holds no rows of its own. Each time you query it, Spark runs the SELECT ... WHERE amount > 100 against orders again.

OR REPLACE matters. Without it, creating a view that already exists fails:

CREATE TEMP VIEW big_orders AS
SELECT * FROM orders
[TEMP_TABLE_OR_VIEW_ALREADY_EXISTS] Cannot create the temporary view `big_orders` because it already exists.

Interview tip: In PySpark, df.createOrReplaceTempView("name") creates exactly this kind of view from a DataFrame. A temp view disappears when the session ends, and another session cannot see it.


4. Global Temporary Views

A global temp view is shared by every session inside the same Spark application. Spark keeps these views in a special database called global_temp, and you must use that prefix to query them:

CREATE OR REPLACE GLOBAL TEMP VIEW daily_totals AS
SELECT order_date, SUM(amount) AS total
FROM orders
GROUP BY order_date
SELECT * FROM global_temp.daily_totals ORDER BY order_date
+----------+-----+
|order_date|total|
+----------+-----+
|2024-01-05|290  |
|2024-01-06|545  |
|2024-01-07|205  |
+----------+-----+

Forgetting the prefix is the most common error with global views:

SELECT * FROM daily_totals
[TABLE_OR_VIEW_NOT_FOUND] The table or view `daily_totals` cannot be found. Verify the spelling and correctness of the schema and catalog.

In practice you will rarely need global temp views. They are mostly used when several notebooks or sessions share one Spark application.


5. Managed Tables

A managed table stores real data. Spark manages both the metadata (name, columns, types) and the data files, which it places in its warehouse folder (spark-warehouse by default).

Create an empty table by listing its columns and a file format with USING:

CREATE TABLE sales (
  order_id INT,
  customer STRING,
  amount   INT
) USING parquet

Add rows with INSERT INTO. You can insert literal values or the result of a query:

INSERT INTO sales VALUES
  (101, 'Asha', 250),
  (102, 'Ben',   40)
INSERT INTO sales
SELECT order_id, customer, amount
FROM orders
WHERE order_id = 104
SELECT * FROM sales ORDER BY order_id
+--------+--------+------+
|order_id|customer|amount|
+--------+--------+------+
|101     |Asha    |250   |
|102     |Ben     |40    |
|104     |Chen    |520   |
+--------+--------+------+

Each INSERT INTO adds rows. The table now holds all three.


6. Replacing Data with INSERT OVERWRITE

INSERT OVERWRITE throws away the current contents and writes the new rows instead:

INSERT OVERWRITE sales
SELECT order_id, customer, amount
FROM orders
WHERE category = 'Electronics'
SELECT * FROM sales ORDER BY order_id
+--------+--------+------+
|order_id|customer|amount|
+--------+--------+------+
|101     |Asha    |250   |
|104     |Chen    |520   |
|106     |Ben     |75    |
+--------+--------+------+

Order 102 (a Books order) is gone, and the table now holds exactly the three Electronics orders: 101, 104 and 106. This is the usual way to rebuild a table on every pipeline run, because running it twice gives the same result. Running INSERT INTO twice would duplicate the rows.

Common mistake: Using INSERT INTO in a job that reruns after a failure. Each retry appends the same rows again. Use INSERT OVERWRITE (or a MERGE on Delta Lake) when a job must be safe to rerun.


7. Create a Table from a Query (CTAS)

CREATE TABLE ... AS SELECT, often called CTAS, creates a table and fills it in one statement. Spark takes the column names and types from the query:

CREATE TABLE customer_totals USING parquet AS
SELECT customer, COUNT(*) AS num_orders, SUM(amount) AS total_amount
FROM orders
GROUP BY customer
SELECT * FROM customer_totals ORDER BY customer
+--------+----------+------------+
|customer|num_orders|total_amount|
+--------+----------+------------+
|Asha    |2         |275         |
|Ben     |2         |115         |
|Chen    |1         |520         |
|Divya   |1         |130         |
+--------+----------+------------+
DESCRIBE customer_totals
+------------+---------+-------+
|col_name    |data_type|comment|
+------------+---------+-------+
|customer    |string   |NULL   |
|num_orders  |bigint   |NULL   |
|total_amount|bigint   |NULL   |
+------------+---------+-------+

COUNT(*) produces a bigint, and SUM of an int column also produces a bigint, which leaves far more room before a large total overflows.

Unlike views, Parquet tables in Spark 3.5 do not support CREATE OR REPLACE TABLE (Delta Lake tables do). Running the same CTAS again fails:

CREATE TABLE customer_totals USING parquet AS
SELECT customer FROM orders
[TABLE_OR_VIEW_ALREADY_EXISTS] Cannot create table or view `spark_catalog`.`default`.`customer_totals` because it already exists.

Add IF NOT EXISTS to skip creation when the table is already there, or DROP TABLE it first to rebuild it.


8. Partitioned Tables

A partitioned table stores its files in one folder per value of a column, such as one folder per date. Queries that filter on that column only read the matching folders. This is called partition pruning, and it is one of the biggest speedups in Spark.

CREATE TABLE orders_by_day (
  order_id   INT,
  customer   STRING,
  amount     INT,
  order_date DATE
) USING parquet
PARTITIONED BY (order_date)
INSERT INTO orders_by_day
SELECT order_id, customer, amount, order_date
FROM orders

SHOW PARTITIONS lists the folders Spark created:

SHOW PARTITIONS orders_by_day
+---------------------+
|partition            |
+---------------------+
|order_date=2024-01-05|
|order_date=2024-01-06|
|order_date=2024-01-07|
+---------------------+

Now a query like this one reads only the order_date=2024-01-06 folder and skips the rest:

SELECT * FROM orders_by_day
WHERE order_date = DATE'2024-01-06'
ORDER BY order_id
+--------+--------+------+----------+
|order_id|customer|amount|order_date|
+--------+--------+------+----------+
|103     |Asha    |25    |2024-01-06|
|104     |Chen    |520   |2024-01-06|
+--------+--------+------+----------+

Common mistake: Partitioning by a column with many distinct values, such as order_id or a timestamp. That creates thousands of tiny folders and files, which makes every query slower. Partition by low-cardinality columns you often filter on, like a date or a country.

Spark always moves partition columns to the end of the table's schema, even if you declare them first. Because INSERT ... SELECT matches columns by position, not by name, put the partition column last in the SELECT.


9. Querying Files Directly

You do not always need a table. Spark SQL can query a folder of files by writing format. followed by the path in backticks.

First, write the orders data out as Parquet files:

INSERT OVERWRITE DIRECTORY '/tmp/spark_sql_tutorial/orders_files'
USING parquet
SELECT * FROM orders

Now query the folder as if it were a table:

SELECT customer, amount
FROM parquet.`/tmp/spark_sql_tutorial/orders_files`
WHERE amount > 100
ORDER BY amount DESC
+--------+------+
|customer|amount|
+--------+------+
|Chen    |520   |
|Asha    |250   |
|Divya   |130   |
+--------+------+

The same pattern works for other formats:

-- Syntax
SELECT * FROM parquet.`/path/to/folder`
SELECT * FROM json.`/path/to/file.json`
SELECT * FROM csv.`/path/to/file.csv`
SELECT * FROM delta.`/path/to/delta_table`   -- needs Delta Lake

This is great for exploring files. For CSV, though, you get no header handling or type inference, so every column comes back as a string named _c0, _c1, and so on. For CSV, create a view or table with options instead.


10. External Tables

An external table points to files at a location you choose with LOCATION. Spark manages the metadata, but you own the files.

Here is a table on top of the Parquet files written in the previous section. Spark reads the schema from the files, so no column list is needed:

CREATE TABLE orders_ext
USING parquet
LOCATION '/tmp/spark_sql_tutorial/orders_files'
SELECT category, COUNT(*) AS num_orders
FROM orders_ext
GROUP BY category
ORDER BY category
+-----------+----------+
|category   |num_orders|
+-----------+----------+
|Books      |2         |
|Electronics|3         |
|Home       |1         |
+-----------+----------+

DESCRIBE EXTENDED shows whether a table is managed or external, among many other details. Its output depends on your machine (times, folder paths), so it is abridged here:

-- Syntax (the full output varies by machine)
DESCRIBE EXTENDED customer_totals
DESCRIBE EXTENDED orders_ext
-- customer_totals (only the Type, Provider and Location rows)
|Type    |MANAGED                                    |
|Provider|parquet                                    |
|Location|file:/.../spark-warehouse/customer_totals  |

-- orders_ext (only the Type, Provider and Location rows)
|Type    |EXTERNAL                                   |
|Provider|parquet                                    |
|Location|file:///tmp/spark_sql_tutorial/orders_files|

11. Listing and Dropping Tables

SHOW TABLES lists everything in the current database, plus your temp views:

SHOW TABLES
+---------+---------------+-----------+
|namespace|tableName      |isTemporary|
+---------+---------------+-----------+
|default  |customer_totals|false      |
|default  |orders_by_day  |false      |
|default  |orders_ext     |false      |
|default  |sales          |false      |
|         |big_orders     |true       |
|         |orders         |true       |
+---------+---------------+-----------+

Tables belong to the default database. Temp views have an empty namespace and isTemporary = true.

Now see the most important difference between managed and external tables. Drop the external table:

DROP TABLE orders_ext

The table is gone from the catalog, but its files are untouched:

SELECT COUNT(*) AS rows_still_on_disk
FROM parquet.`/tmp/spark_sql_tutorial/orders_files`
+------------------+
|rows_still_on_disk|
+------------------+
|6                 |
+------------------+

Dropping a managed table, on the other hand, deletes its data files too:

DROP TABLE sales

Dropping something that does not exist raises an error, so scripts usually add IF EXISTS:

DROP TABLE IF EXISTS sales

Views are dropped with DROP VIEW:

DROP VIEW IF EXISTS big_orders

Interview tip: "What happens to the data when you drop a managed table versus an external table?" is a classic question. Managed: metadata and data are deleted. External: only the metadata is deleted, and the files stay where they are.


12. What About UPDATE, DELETE and MERGE?

Plain Parquet tables only support adding and overwriting data. Row-level changes fail:

UPDATE customer_totals SET total_amount = 0 WHERE customer = 'Ben'
UPDATE TABLE is not supported temporarily.
DELETE FROM customer_totals WHERE customer = 'Ben'
[UNSUPPORTED_FEATURE.TABLE_OPERATION] The feature is not supported: Table `spark_catalog`.`default`.`customer_totals` does not support DELETE. Please check the current catalog and namespace to make sure the qualified table name is expected, and also check the catalog implementation which is configured by "spark.sql.catalog".

The UPDATE message is oddly worded, but both errors mean the same thing: Parquet files cannot be changed row by row. To update, delete or merge individual rows, you need a table format that supports it, such as Delta Lake (the default table format on Databricks) or Apache Iceberg. With Delta Lake, statements like these work:

-- Syntax (needs a Delta Lake table)
UPDATE customers SET city = 'Pune' WHERE customer_id = 7;

DELETE FROM customers WHERE is_active = false;

MERGE INTO customers AS t
USING customer_updates AS s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

13. Try It in the Online Compiler

Copy this into the PySpark Online Compiler. It builds a view, a table from a query, and a partitioned table:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL Tables").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW orders AS
SELECT * FROM VALUES
  (101, 'Asha',  DATE'2024-01-05', 'Electronics', 250),
  (102, 'Ben',   DATE'2024-01-05', 'Books',        40),
  (103, 'Asha',  DATE'2024-01-06', 'Books',        25),
  (104, 'Chen',  DATE'2024-01-06', 'Electronics', 520),
  (105, 'Divya', DATE'2024-01-07', 'Home',        130),
  (106, 'Ben',   DATE'2024-01-07', 'Electronics',  75)
AS orders(order_id, customer, order_date, category, amount)
""")

# A view is a saved query
spark.sql("""
CREATE OR REPLACE TEMP VIEW big_orders AS
SELECT order_id, customer, amount FROM orders WHERE amount > 100
""")
spark.sql("SELECT * FROM big_orders ORDER BY order_id").show(truncate=False)

# A partitioned managed table, rebuilt on every run
spark.sql("DROP TABLE IF EXISTS orders_by_day")
spark.sql("""
CREATE TABLE orders_by_day (order_id INT, customer STRING, amount INT, order_date DATE)
USING parquet
PARTITIONED BY (order_date)
""")
spark.sql("INSERT INTO orders_by_day SELECT order_id, customer, amount, order_date FROM orders")
spark.sql("SHOW PARTITIONS orders_by_day").show(truncate=False)
spark.sql("SHOW TABLES").show(truncate=False)

Summary

  • A view is a saved query and stores no data; a table points to data files.
  • CREATE OR REPLACE TEMP VIEW is the everyday way to name a query. Global temp views live in global_temp and need that prefix.
  • CREATE TABLE ... USING parquet makes a managed table; INSERT INTO appends and INSERT OVERWRITE replaces.
  • CTAS (CREATE TABLE ... AS SELECT) creates and fills a table in one step.
  • PARTITIONED BY splits data into folders so filters on that column read less data.
  • parquet.`/path` queries files directly; LOCATION creates an external table over existing files.
  • Dropping a managed table deletes its data; dropping an external table keeps the files.
  • UPDATE, DELETE and MERGE need a table format such as Delta Lake.

Next, you will learn how to select, rename and sort columns with SELECT and ORDER BY.