โ UNION, INTERSECT & EXCEPT
Joins put tables side by side. Set operations stack query results on top of each other: UNION combines them, INTERSECT keeps rows found in both, and EXCEPT keeps rows found in one but not the other.
This tutorial covers all three, their ALL versions, and the rules that decide how columns line up.
Sample Data
We use two small views of customer orders, one row per order. Some customers ordered more than once, and Divya's city is unknown:
CREATE OR REPLACE TEMP VIEW jan_orders AS
SELECT * FROM VALUES
('Asha', 'Pune'),
('Ben', 'Mumbai'),
('Chen', 'Delhi'),
('Chen', 'Delhi'),
('Chen', 'Delhi'),
('Divya', NULL)
AS jan_orders(customer, city)
CREATE OR REPLACE TEMP VIEW feb_orders AS
SELECT * FROM VALUES
('Ben', 'Mumbai'),
('Chen', 'Delhi'),
('Chen', 'Delhi'),
('Divya', NULL),
('Elena', 'Pune')
AS feb_orders(customer, city)
In short: Asha ordered only in January, Elena only in February, and Ben, Chen and Divya ordered in both months.
1. The Rules of Set Operations
A set operation sits between two complete SELECT queries:
-- Syntax
SELECT col1, col2 FROM table_a
UNION | UNION ALL | INTERSECT | EXCEPT
SELECT col1, col2 FROM table_b
Both queries must follow three rules:
- They return the same number of columns.
- Columns in the same position have compatible types.
- Columns are matched by position, not by name. The output column names come from the first query.
2. UNION ALL: Stack Everything
UNION ALL appends the rows of the second query to the first, keeping every row, duplicates included:
SELECT customer, city FROM jan_orders
UNION ALL
SELECT customer, city FROM feb_orders
ORDER BY customer
+--------+------+
|customer|city |
+--------+------+
|Asha |Pune |
|Ben |Mumbai|
|Ben |Mumbai|
|Chen |Delhi |
|Chen |Delhi |
|Chen |Delhi |
|Chen |Delhi |
|Chen |Delhi |
|Divya |NULL |
|Divya |NULL |
|Elena |Pune |
+--------+------+
6 January rows plus 5 February rows gives 11 rows. UNION ALL is the right choice when you combine data from different sources or periods, such as daily files into one table.
3. UNION: Stack and Remove Duplicates
UNION (also written UNION DISTINCT) does the same, then removes duplicate rows from the combined result:
SELECT customer, city FROM jan_orders
UNION
SELECT customer, city FROM feb_orders
ORDER BY customer
+--------+------+
|customer|city |
+--------+------+
|Asha |Pune |
|Ben |Mumbai|
|Chen |Delhi |
|Divya |NULL |
|Elena |Pune |
+--------+------+
Each distinct customer and city appears once. Chen's five orders collapse into one row.
UNION ALL | UNION | |
|---|---|---|
| Duplicates | Kept | Removed |
| Speed | Fast: rows are appended | Slower: Spark must compare all rows to find duplicates, which needs a shuffle |
| Use when | You want every row, or you know there are no duplicates | You need a distinct list |
Common mistake: Using
UNIONby habit. On large tables, the duplicate removal is expensive, and it can also delete rows you meant to keep, such as two genuine orders with the same values. Default toUNION ALLand useUNIONonly when you want duplicates gone.
4. Columns Are Matched by Position, Not Name
Spark does not look at column names when stacking results. If the second query lists its columns in a different order, the values land in the wrong columns, and no error is raised:
SELECT customer, city FROM jan_orders WHERE customer = 'Asha'
UNION ALL
SELECT city, customer FROM feb_orders WHERE customer = 'Elena'
+--------+-----+
|customer|city |
+--------+-----+
|Asha |Pune |
|Pune |Elena|
+--------+-----+
Elena's city ended up in the customer column. Both columns are strings, so Spark had no reason to complain.
Always list columns explicitly, in the same order, in every branch. Avoid SELECT * in set operations, because a column added to one table later shifts everything silently. Spark 3.5 SQL has no option to match columns by name, but in PySpark the DataFrame method unionByName() does exactly that.
5. Different Column Counts Fail
If the two queries return a different number of columns, Spark refuses to run the query:
SELECT customer, city FROM jan_orders
UNION
SELECT customer FROM feb_orders
[NUM_COLUMNS_MISMATCH] UNION can only be performed on inputs with the same number of columns, but the first input has 2 columns and the second input has 1 columns.; line 1 pos 0;
To stack tables that do not have the same columns, add the missing ones as NULL with an explicit type, for example SELECT customer, CAST(NULL AS STRING) AS city FROM ....
6. INTERSECT: Rows Found in Both
INTERSECT returns the distinct rows that appear in both results. Which customers ordered in both January and February?
SELECT customer FROM jan_orders
INTERSECT
SELECT customer FROM feb_orders
ORDER BY customer
+--------+
|customer|
+--------+
|Ben |
|Chen |
|Divya |
+--------+
Ben, Chen and Divya, each once. Like UNION, plain INTERSECT removes duplicates.
7. EXCEPT: Rows Found in the First but Not the Second
EXCEPT returns distinct rows from the first query that do not appear in the second. Which customers ordered in January but not in February?
SELECT customer FROM jan_orders
EXCEPT
SELECT customer FROM feb_orders
+--------+
|customer|
+--------+
|Asha |
+--------+
Unlike UNION and INTERSECT, order matters for EXCEPT. Swap the queries and you get the new customers in February instead:
SELECT customer FROM feb_orders
EXCEPT
SELECT customer FROM jan_orders
+--------+
|customer|
+--------+
|Elena |
+--------+
Spark also accepts MINUS, the Oracle name for the same operation:
SELECT customer FROM jan_orders
MINUS
SELECT customer FROM feb_orders
+--------+
|customer|
+--------+
|Asha |
+--------+
Interview tip:
EXCEPTis a quick way to compare two versions of a table. RunA EXCEPT BandB EXCEPT A. If both return nothing, the tables contain the same distinct rows.
8. INTERSECT ALL and EXCEPT ALL: Counting Duplicates
The ALL versions keep duplicates and work by count, row by row:
INTERSECT ALL: a row appears as many times as the smaller of its two counts.EXCEPT ALL: a row appears as many times as its count in the first query minus its count in the second (if that is above zero).
Chen ordered 3 times in January and 2 times in February:
SELECT customer FROM jan_orders
INTERSECT ALL
SELECT customer FROM feb_orders
ORDER BY customer
+--------+
|customer|
+--------+
|Ben |
|Chen |
|Chen |
|Divya |
+--------+
Chen appears twice: the smaller of 3 and 2.
SELECT customer FROM jan_orders
EXCEPT ALL
SELECT customer FROM feb_orders
ORDER BY customer
+--------+
|customer|
+--------+
|Asha |
|Chen |
+--------+
Asha (1 - 0 = 1) and one Chen (3 - 2 = 1) remain. Ben and Divya ordered once in each month, so 1 - 1 = 0 removes them.
9. NULLs Are Treated as Equal
In a WHERE clause or a join, NULL = NULL is not true (see Handling NULLs). Set operations are different: when comparing rows, two NULLs count as the same value.
SELECT customer, city FROM jan_orders
INTERSECT
SELECT customer, city FROM feb_orders
ORDER BY customer
+--------+------+
|customer|city |
+--------+------+
|Ben |Mumbai|
|Chen |Delhi |
|Divya |NULL |
+--------+------+
Divya's row (Divya, NULL) is in both views, and INTERSECT matches it. A join on customer and city with = would have missed her. This makes INTERSECT and EXCEPT handy for comparing tables that contain NULLs.
10. Types and Column Names Come from the Combined Result
When the column types differ, Spark picks a type that fits both, as long as they are compatible. The names always come from the first query, so aliases in later branches are ignored:
SELECT value, typeof(value) AS value_type
FROM (
SELECT 1 AS value
UNION ALL
SELECT 2.5 AS another_name
)
ORDER BY value
+-----+-------------+
|value|value_type |
+-----+-------------+
|1.0 |decimal(11,1)|
|2.5 |decimal(11,1)|
+-----+-------------+
The integer 1 was widened to a decimal so both rows fit one column, and the column is called value, not another_name.
Widening only goes so far. On Spark 3.5 with default settings, combining 1 with 'a' turns the column into a string, but with ANSI mode on (the default in Spark 4.0 and Databricks SQL) the same query fails. A DATE and an INT cannot be combined at all. Cast explicitly with CAST(col AS type) when the branches do not already match.
11. ORDER BY and LIMIT Apply to the Whole Result
An ORDER BY or LIMIT written after the last query applies to the combined result, not only to the last branch:
SELECT customer FROM jan_orders
UNION
SELECT customer FROM feb_orders
ORDER BY customer DESC
LIMIT 3
+--------+
|customer|
+--------+
|Elena |
|Divya |
|Chen |
+--------+
All five distinct customers are combined first, then sorted and cut to three. To sort or limit a single branch before combining, wrap it in parentheses or a subquery.
Set Operations at a Glance
| Operation | Returns | Duplicates | Order of queries matters? |
|---|---|---|---|
UNION ALL | All rows from both | Kept | No (except row order) |
UNION | All rows from both | Removed | No |
INTERSECT | Rows in both | Removed | No |
INTERSECT ALL | Rows in both, by count | Kept (smaller count) | No |
EXCEPT / MINUS | Rows in first, not in second | Removed | Yes |
EXCEPT ALL | Rows in first, not in second, by count | Kept (count difference) | Yes |
Try It in the Online Compiler
Copy this into the PySpark Online Compiler to compare the months yourself:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Set Operations").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW jan_orders AS
SELECT * FROM VALUES
('Asha', 'Pune'), ('Ben', 'Mumbai'), ('Chen', 'Delhi'),
('Chen', 'Delhi'), ('Chen', 'Delhi'), ('Divya', NULL)
AS jan_orders(customer, city)
""")
spark.sql("""
CREATE OR REPLACE TEMP VIEW feb_orders AS
SELECT * FROM VALUES
('Ben', 'Mumbai'), ('Chen', 'Delhi'), ('Chen', 'Delhi'),
('Divya', NULL), ('Elena', 'Pune')
AS feb_orders(customer, city)
""")
# Customers who ordered in both months
spark.sql("""
SELECT customer FROM jan_orders
INTERSECT
SELECT customer FROM feb_orders
ORDER BY customer
""").show(truncate=False)
# January-only customers
spark.sql("""
SELECT customer FROM jan_orders
EXCEPT
SELECT customer FROM feb_orders
""").show(truncate=False)
# Every order from both months
spark.sql("""
SELECT customer, city FROM jan_orders
UNION ALL
SELECT customer, city FROM feb_orders
ORDER BY customer
""").show(truncate=False)
Summary
- Set operations combine two queries with the same number of columns, matched by position. Names come from the first query.
UNION ALLkeeps every row and is fast;UNIONremoves duplicates and needs extra work.INTERSECTreturns rows found in both queries;EXCEPT(orMINUS) returns rows in the first but not the second, so its order matters.INTERSECT ALLandEXCEPT ALLkeep duplicates and work by count.- Set operations treat two NULLs as equal, unlike
=inWHEREand joins. ORDER BYandLIMITafter the last query apply to the combined result.
Next, you will learn to nest queries inside queries with subqueries and CTEs.