Spark SQL Reference
Run declarative SQL queries, catalog operations, temporary views, and execution plan analysis directly in PySpark.
Creates or replaces a session-scoped temporary view bound to the current SparkSession.
Used In: Ad-hoc SQL Querying, Hybrid DataFrame/SQL Workflows
df.createOrReplaceTempView(name)df.createOrReplaceTempView('employees')
spark.sql('SELECT department, AVG(salary) FROM employees GROUP BY department').show()| department | avg(salary) |
|---|---|
| Engineering | 95000.0 |
| Marketing | 68000.0 |
Creates a cross-session global temporary view tied to the system database `global_temp`.
Used In: Multi-session Pipelines, Shared In-memory Datasets
df.createGlobalTempView(name)df.createGlobalTempView('global_sales')
# Query from any session using global_temp qualification:
spark.sql('SELECT SUM(amount) FROM global_temp.global_sales').show()| sum(amount |
|---|
| 1500000.0 |
Executes an inline SQL query string and returns the output as a PySpark DataFrame.
Used In: Complex Analytical Queries, CTEs, Window Functions, Subqueries
spark.sql(sqlQuery)res = spark.sql('''
WITH RankedEmps AS (
SELECT emp_id, name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rnk
FROM employees
)
SELECT * FROM RankedEmps WHERE rnk <= 3
''')| emp_id | name | department | salary | rnk |
|---|---|---|---|---|
| 101 | Alice | Engineering | 120000 | 1 |
| 105 | Bob | Engineering | 110000 | 2 |
Inspects and lists all registered tables/views in the current database catalog.
Used In: Catalog Audits, Dynamic Pipeline Automation
spark.catalog.listTables(dbName=None)tables = spark.catalog.listTables()
for t in tables:
print(t.name, t.isTemporary, t.tableType)employees True TEMPORARY
global_sales True TEMPORARYPrints the Catalyst execution plans (Parsed, Analyzed, Optimized, Physical Plan) to console.
Used In: Performance Tuning, Bottleneck Diagnosis, Join Debugging
df.explain(extended=True) # or mode='formatted' / 'cost'spark.sql('SELECT * FROM employees WHERE salary > 80000').explain(mode='formatted')== Physical Plan ==
*(1) Filter (salary#5 > 80000)
+- *(1) Scan ExistingRDD[emp_id#4,name#5,salary#6]Removes a cached table or view from Spark executor memory and disk storage.
Used In: Memory Management, Resource Reclamation
spark.catalog.uncacheTable(tableName)spark.catalog.cacheTable('employees')
# After query completes:
spark.catalog.uncacheTable('employees')Table uncached from memory