โšก Introduction to Spark SQL

Spark SQL lets you query big data with plain SQL. If you can write SELECT name FROM employees WHERE salary > 50000, you can already process terabytes of data on a Spark cluster, because Spark takes care of splitting the work across machines for you.

This tutorial series teaches Spark SQL from the very first query to advanced topics like window functions and query plans. Every query comes with the exact result it produces, so you can follow along even before you run anything.


1. What is Spark SQL?

Apache Spark is an engine for processing large datasets in parallel. Spark SQL is the part of Spark that understands SQL and tables.

There are two ways to tell Spark what to do with your data:

ApproachExample
SQLSELECT dept, COUNT(*) FROM employees GROUP BY dept
DataFrame API (PySpark, Scala)df.groupBy("dept").count()

Both go through the same optimizer (called Catalyst) and end up as the same execution plan. So SQL is not a "slower" or "simpler" option. Pick whichever reads better for the task, and mix them freely.

Why learn Spark SQL?

  • Most data engineering is SQL. Pipelines in Databricks, EMR, Synapse and Fabric are full of Spark SQL.
  • It is the shared language of data teams. Analysts, engineers and scientists can all read it.
  • Interviews test it. Joins, window functions and GROUP BY questions come up in almost every data engineering interview.

2. Where Can You Run Spark SQL?

You can run the same SQL in several places:

WhereHow
PySpark (including our online compiler)spark.sql("SELECT ...").show()
Databricks notebooksA cell that starts with %sql, or a SQL notebook
Databricks SQL editorType the query and click Run
spark-sql shellRun spark-sql in a terminal where Spark is installed

In PySpark, spark.sql() takes one statement at a time and returns a DataFrame. Call .show() on it to print the result:

from pyspark.sql import SparkSession

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

spark.sql("SELECT 'Hello, Spark SQL' AS greeting, 1 + 1 AS two").show()

Tip: Use triple quotes (""") for queries that span several lines, and .show(truncate=False) so long values are not cut off at 20 characters.

In the rest of this series, the queries are written as plain SQL. Paste them into a %sql cell as they are, or wrap each statement in spark.sql("""...""") in PySpark.


3. Your First Query

A SELECT does not even need a table. You can use Spark SQL as a calculator:

SELECT 'Hello, Spark SQL' AS greeting,
       1 + 1              AS two,
       upper('spark')     AS shout
+----------------+---+-----+
|greeting        |two|shout|
+----------------+---+-----+
|Hello, Spark SQL|2  |SPARK|
+----------------+---+-----+

AS gives each column a name. Without it, Spark names the column after the expression itself, such as (1 + 1).


4. Creating Sample Data

To query data, Spark needs a table or a view. The quickest way to get one is a temporary view built from inline rows with VALUES:

CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)

Here is what each part does:

  • CREATE OR REPLACE TEMP VIEW employees creates a view called employees, or replaces it if it already exists.
  • VALUES (...), (...) lists the rows.
  • AS employees(emp_id, name, ...) names the columns.
  • DATE'2019-03-15' is a date literal, so hire_date gets the DATE type instead of plain text.

A temp view lives only as long as your Spark session. It stores no data on disk; it is just a name for a query. That makes it perfect for learning.

Now query it:

SELECT * FROM employees
+------+-----+-----------+------+----------+----------+---------+
|emp_id|name |dept       |salary|hire_date |manager_id|city     |
+------+-----+-----------+------+----------+----------+---------+
|1     |Asha |Engineering|95000 |2019-03-15|NULL      |Bengaluru|
|2     |Ben  |Engineering|82000 |2020-07-01|1         |Pune     |
|3     |Chen |Sales      |60000 |2021-01-10|1         |Mumbai   |
|4     |Divya|Sales      |65000 |2018-11-23|3         |Mumbai   |
|5     |Elena|Marketing  |58000 |2022-05-30|1         |NULL     |
|6     |Farid|Engineering|82000 |2023-02-14|2         |Bengaluru|
|7     |Grace|NULL       |45000 |2024-01-08|NULL      |Delhi    |
+------+-----+-----------+------+----------+----------+---------+

SELECT * returns every column. Notice the NULL values: Grace has no department, Elena has no city, and Asha and Grace have no manager. NULL means "unknown", and later tutorials show how to handle it.

This employees view is used throughout the series, so keep this snippet handy.


5. Checking a Table's Columns and Types

DESCRIBE lists the columns of a table or view with their data types:

DESCRIBE employees
+----------+---------+-------+
|col_name  |data_type|comment|
+----------+---------+-------+
|emp_id    |int      |NULL   |
|name      |string   |NULL   |
|dept      |string   |NULL   |
|salary    |int      |NULL   |
|hire_date |date     |NULL   |
|manager_id|int      |NULL   |
|city      |string   |NULL   |
+----------+---------+-------+

Spark worked out the types from the values: whole numbers became int, text became string, and the DATE'...' literals became date.

SHOW TABLES lists the tables and views you can query. Temporary views show isTemporary = true:

SHOW TABLES
+---------+---------+-----------+
|namespace|tableName|isTemporary|
+---------+---------+-----------+
|         |employees|true       |
+---------+---------+-----------+

6. The Shape of a SQL Query

Most queries you write will follow this template. Only SELECT is required; the other clauses are optional, but they must appear in this order:

-- Syntax
SELECT   columns or expressions
FROM     table
WHERE    row filter
GROUP BY grouping columns
HAVING   group filter
ORDER BY sort columns
LIMIT    number of rows

Here is a query that uses all of them. It finds departments whose employees earn more than 50,000 on average, highest average first:

SELECT   dept,
         COUNT(*)    AS headcount,
         AVG(salary) AS avg_salary
FROM     employees
WHERE    dept IS NOT NULL
GROUP BY dept
HAVING   AVG(salary) > 50000
ORDER BY avg_salary DESC
LIMIT    10
+-----------+---------+-----------------+
|dept       |headcount|avg_salary       |
+-----------+---------+-----------------+
|Engineering|3        |86333.33333333333|
|Sales      |2        |62500.0          |
|Marketing  |1        |58000.0          |
+-----------+---------+-----------------+

You write the clauses in one order, but Spark evaluates them in another:

StepClauseWhat happens
1FROMPick the table
2WHEREDrop rows that fail the filter (Grace, with no department)
3GROUP BYPut the remaining rows into one group per dept
4HAVINGDrop groups that fail the filter
5SELECTCompute the output columns
6ORDER BYSort the result
7LIMITKeep the first N rows

This order explains many beginner errors. For example, WHERE runs before SELECT, which is why you cannot filter on the alias avg_salary in WHERE. ORDER BY runs after SELECT, so it can use the alias. You will meet each of these clauses in detail in the next tutorials.


7. Spark SQL and DataFrames Work Together

In PySpark you can switch between SQL and DataFrames at any point:

  • df.createOrReplaceTempView("name") turns a DataFrame into a view you can query with SQL.
  • spark.sql(...) returns a DataFrame, so you can keep transforming it with the DataFrame API.
  • spark.table("name") gives you a view or table back as a DataFrame.
from pyspark.sql import SparkSession

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

# DataFrame -> SQL
orders = spark.createDataFrame(
    [(101, "Asha", 250), (102, "Ben", 120), (103, "Asha", 80)],
    ["order_id", "customer", "amount"],
)
orders.createOrReplaceTempView("orders")

# SQL -> DataFrame
totals = spark.sql("""
    SELECT customer, SUM(amount) AS total
    FROM orders
    GROUP BY customer
""")

# Keep going with the DataFrame API
totals.orderBy("customer").show()

Like the DataFrame API, Spark SQL is lazy. spark.sql(...) only plans the query; nothing runs until you call an action such as .show(), .count() or .collect().


8. Try It in the Online Compiler

Copy this into the PySpark Online Compiler to create the sample data and run your first queries. Each spark.sql() call holds one statement:

from pyspark.sql import SparkSession

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

spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")

spark.sql("SELECT * FROM employees").show(truncate=False)

spark.sql("""
SELECT dept, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY avg_salary DESC
""").show(truncate=False)

Summary

  • Spark SQL runs standard SQL on Spark, with the same optimizer and speed as the DataFrame API.
  • In PySpark, run queries with spark.sql("..."), one statement per call, and print them with .show().
  • CREATE OR REPLACE TEMP VIEW ... AS SELECT * FROM VALUES ... is the quickest way to make sample data.
  • DESCRIBE shows a table's columns and types; SHOW TABLES lists what you can query.
  • Clauses are written SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT but evaluated starting with FROM.

Next, you will learn the different kinds of tables and views in Spark and when to use each one.