๐Ÿงฉ Subqueries & CTEs

A subquery is a query inside another query. A CTE (common table expression) is a named subquery you define up front with WITH. Both let you break a hard question into smaller steps, such as "first find the average salary, then find who earns more than it".

This tutorial covers scalar, IN, EXISTS and correlated subqueries, subqueries in FROM, and how to write clean multi-step queries with CTEs.


Sample Data

We use the employees view from the introduction and the departments view from Joins:

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)
CREATE OR REPLACE TEMP VIEW departments AS
SELECT * FROM VALUES
  ('Engineering', 3, 500000),
  ('Sales',       2, 200000),
  ('Marketing',   2, 150000),
  ('HR',          1,  80000)
AS departments(dept, floor, budget)

1. Where Subqueries Can Go

A subquery is always written in parentheses. Depending on what it returns, you can use it in different places:

Subquery returnsCalledUsed inExample
One value (1 row, 1 column)Scalar subquerySELECT, WHERE, anywhere a value fitssalary > (SELECT AVG(salary) FROM employees)
One column, many rowsList subqueryIN / NOT INdept IN (SELECT dept FROM departments)
Any rowsExistence checkEXISTS / NOT EXISTSEXISTS (SELECT 1 FROM ...)
A whole tableDerived tableFROMFROM (SELECT ...) AS t

2. Scalar Subquery in WHERE

Who earns more than the company average? You cannot write WHERE salary > AVG(salary), because WHERE looks at one row at a time and an average needs all rows. A scalar subquery computes the average first:

SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC
+-----+------+
|name |salary|
+-----+------+
|Asha |95000 |
|Ben  |82000 |
|Farid|82000 |
+-----+------+

Spark runs the inner query once (the average is about 69,571) and then uses that single value in the filter, just as if you had typed the number.


3. Scalar Subquery in SELECT

A scalar subquery can also be a column. Here each employee is compared to the company average:

SELECT name,
       salary,
       ROUND(salary - (SELECT AVG(salary) FROM employees), 0) AS diff_from_avg
FROM employees
ORDER BY diff_from_avg DESC
+-----+------+-------------+
|name |salary|diff_from_avg|
+-----+------+-------------+
|Asha |95000 |25429.0      |
|Ben  |82000 |12429.0      |
|Farid|82000 |12429.0      |
|Divya|65000 |-4571.0      |
|Chen |60000 |-9571.0      |
|Elena|58000 |-11571.0     |
|Grace|45000 |-24571.0     |
+-----+------+-------------+

The subquery gives the same value on every row. Positive numbers are above average, negative numbers below.


4. A Scalar Subquery Must Return One Row

If a subquery used as a value returns more than one row, Spark does not know which one to use, and the query fails when it runs:

SELECT name
FROM employees
WHERE salary = (SELECT salary FROM employees WHERE dept = 'Engineering')
[SCALAR_SUBQUERY_TOO_MANY_ROWS] More than one row returned by a subquery used as an expression.

Engineering has three employees, so the subquery returns three salaries. In PySpark, this error is raised when you call .show(), not when you call spark.sql(), because Spark only finds out how many rows the subquery returns while running it. Fix it by making the subquery return one value (with MAX, MIN, AVG and so on), or switch to IN if you mean "equal to any of them".


5. IN Subquery: Match Any Value in a List

IN (subquery) keeps rows whose value appears anywhere in the subquery's single column. Who works in a department on floor 2?

SELECT name, dept
FROM employees
WHERE dept IN (SELECT dept FROM departments WHERE floor = 2)
ORDER BY emp_id
+-----+---------+
|name |dept     |
+-----+---------+
|Chen |Sales    |
|Divya|Sales    |
|Elena|Marketing|
+-----+---------+

The subquery returns Sales and Marketing, and the outer query keeps employees from those departments. This works like a semi join: each employee appears at most once, no matter how many rows match.


6. Correlated Subqueries: The Inner Query Uses the Outer Row

The subqueries so far were independent of the outer query. A correlated subquery refers to a column of the outer query, so its result changes from row to row.

Who earns more than the average of their own department?

SELECT e.name, e.dept, e.salary
FROM employees e
WHERE e.salary > (
  SELECT AVG(e2.salary)
  FROM employees e2
  WHERE e2.dept = e.dept
)
ORDER BY e.dept, e.name
+-----+-----------+------+
|name |dept       |salary|
+-----+-----------+------+
|Asha |Engineering|95000 |
|Divya|Sales      |65000 |
+-----+-----------+------+

Read it from the outer row's point of view. For Asha, the subquery averages Engineering salaries (about 86,333), and 95,000 is above it. For Divya, it averages Sales (62,500). Elena is the only person in Marketing, so she equals her department average and is not above it. Grace's dept is NULL, so e2.dept = e.dept never matches, her average is NULL, and she is filtered out.

The aliases e and e2 are essential here: they tell Spark which dept belongs to the outer query and which to the inner one.

Spark does not literally rerun the subquery for each row. It rewrites correlated subqueries into joins and aggregations, so they scale to large tables.


7. EXISTS and NOT EXISTS

EXISTS (subquery) is true when the subquery returns at least one row. What the rows contain does not matter, which is why people often write SELECT 1 inside it.

Which departments have at least one employee?

SELECT d.dept
FROM departments d
WHERE EXISTS (
  SELECT 1 FROM employees e WHERE e.dept = d.dept
)
ORDER BY d.dept
+-----------+
|dept       |
+-----------+
|Engineering|
|Marketing  |
|Sales      |
+-----------+

NOT EXISTS finds the opposite, the departments with no employees:

SELECT d.dept
FROM departments d
WHERE NOT EXISTS (
  SELECT 1 FROM employees e WHERE e.dept = d.dept
)
+----+
|dept|
+----+
|HR  |
+----+

These are the SQL-standard way to write a semi join and an anti join. Spark turns them into a LEFT SEMI JOIN and a LEFT ANTI JOIN, which you met in Joins.


8. NOT IN vs NOT EXISTS When NULLs Are Around

The two look interchangeable, but they disagree when the subquery contains a NULL. Let us find employees who do not manage anybody. With NOT IN:

SELECT name
FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees)
+----+
|name|
+----+
+----+

No rows at all. manager_id contains NULLs, and x NOT IN (..., NULL) can never be true (the Handling NULLs tutorial explains why). NOT EXISTS only checks whether a matching row exists, so NULLs do no harm:

SELECT e.name
FROM employees e
WHERE NOT EXISTS (
  SELECT 1 FROM employees r WHERE r.manager_id = e.emp_id
)
ORDER BY e.emp_id
+-----+
|name |
+-----+
|Divya|
|Elena|
|Farid|
|Grace|
+-----+

Common mistake: Using NOT IN (subquery) on a column that may contain NULL. Prefer NOT EXISTS (or LEFT ANTI JOIN), or add WHERE column IS NOT NULL inside the subquery. This difference is a popular interview question.


9. Subqueries in FROM (Derived Tables)

A subquery in FROM acts like a temporary table that exists only for this query. It is useful when you need to filter or join on a result that you first have to compute.

Which departments have at least two employees, and what is their average salary?

SELECT dept, headcount, avg_salary
FROM (
  SELECT dept,
         COUNT(*)    AS headcount,
         AVG(salary) AS avg_salary
  FROM employees
  GROUP BY dept
) AS dept_stats
WHERE headcount >= 2
ORDER BY dept
+-----------+---------+-----------------+
|dept       |headcount|avg_salary       |
+-----------+---------+-----------------+
|Engineering|3        |86333.33333333333|
|Sales      |2        |62500.0          |
+-----------+---------+-----------------+

(For this particular question HAVING COUNT(*) >= 2 would also work. Derived tables become necessary when the next step is a join, another aggregation, or a filter on a computed column.)

Give every derived table an alias like AS dept_stats. It lets you refer to its columns as dept_stats.dept, and it makes the query easier to read.


10. CTEs: Naming Your Steps with WITH

Nested subqueries get hard to read quickly, because you have to read them from the inside out. A CTE moves the subquery to the top and gives it a name:

-- Syntax
WITH step_name AS (
  SELECT ...
)
SELECT ...
FROM step_name

Here is the query from section 9, rewritten with a CTE:

WITH dept_stats AS (
  SELECT dept,
         COUNT(*)    AS headcount,
         AVG(salary) AS avg_salary
  FROM employees
  GROUP BY dept
)
SELECT dept, headcount, avg_salary
FROM dept_stats
WHERE headcount >= 2
ORDER BY dept
+-----------+---------+-----------------+
|dept       |headcount|avg_salary       |
+-----------+---------+-----------------+
|Engineering|3        |86333.33333333333|
|Sales      |2        |62500.0          |
+-----------+---------+-----------------+

Same result, but the query now reads top to bottom: first build dept_stats, then filter it.


11. Chaining Several CTEs

You can define several CTEs, separated by commas. Each one can use the ones defined before it, which lets you build a query step by step.

Find the highest-paid person in each department, with the floor they work on:

WITH dept_max AS (
  SELECT dept, MAX(salary) AS max_salary
  FROM employees
  WHERE dept IS NOT NULL
  GROUP BY dept
),
top_earners AS (
  SELECT e.dept, e.name, e.salary
  FROM employees e
  JOIN dept_max m
    ON  e.dept   = m.dept
    AND e.salary = m.max_salary
)
SELECT t.dept, t.name, t.salary, d.floor
FROM top_earners t
JOIN departments d
  ON t.dept = d.dept
ORDER BY t.dept
+-----------+-----+------+-----+
|dept       |name |salary|floor|
+-----------+-----+------+-----+
|Engineering|Asha |95000 |3    |
|Marketing  |Elena|58000 |2    |
|Sales      |Divya|65000 |2    |
+-----------+-----+------+-----+
  1. dept_max finds the top salary per department.
  2. top_earners joins back to employees to find who earns it. If two people tied, both would appear.
  3. The final SELECT adds the floor from departments.

Each step can be tested on its own by temporarily selecting from it, which makes CTEs much easier to debug than nested subqueries. (The window functions tutorial shows another way to solve "top N per group".)

Interview tip: Interviewers like candidates who structure long queries as named CTE steps. It shows you can break a problem down, and it makes your answer easy to follow.


12. CTE, Subquery or Temp View?

All three name or wrap a query, but they live for different lengths of time:

SubqueryCTE (WITH)Temp view
Lives forOne spot in one queryOne statementThe whole Spark session
ReuseNo; repeat it to use it twiceCan be referenced several times in the same statementAny later query can use it
ReadabilityFine when shortBest for multi-step logicGood for sharing a step across queries
Stores data?NoNoNo

None of them store data. A CTE or temp view is just a named query; Spark folds it into the plan of whatever query uses it. If an expensive step is used by many later queries, save it to a table or cache it instead of recomputing it each time. The Tables & Views tutorial covers those options.


Try It in the Online Compiler

Copy this into the PySpark Online Compiler to run a correlated subquery and a CTE:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL Subqueries").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)
""")

# Who earns more than their department's average?
spark.sql("""
SELECT e.name, e.dept, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.dept = e.dept)
ORDER BY e.dept, e.name
""").show(truncate=False)

# Departments with at least two people, as a CTE
spark.sql("""
WITH dept_stats AS (
  SELECT dept, COUNT(*) AS headcount, AVG(salary) AS avg_salary
  FROM employees
  GROUP BY dept
)
SELECT * FROM dept_stats
WHERE headcount >= 2
ORDER BY dept
""").show(truncate=False)

Summary

  • A scalar subquery returns one value and can be used wherever a value fits, in SELECT or WHERE. If it returns more than one row, the query fails.
  • IN (subquery) matches any value in a one-column result; EXISTS checks whether any row exists.
  • A correlated subquery refers to the outer row, for example to compare each employee with their own department.
  • NOT IN returns nothing when the subquery contains a NULL; NOT EXISTS does not have this problem.
  • A subquery in FROM is a derived table; give it an alias.
  • CTEs (WITH name AS (...)) turn nested subqueries into readable, named steps that can be chained.
  • Subqueries and CTEs live inside one statement, temp views live for the session, and none of them store data.

That completes the Spark SQL basics. Next, the advanced section starts with string functions for cleaning and reshaping text.