Updated on 2026-11-06 GMT+08:00

EXCEPT

Function

EXCEPT returns the set difference of two query results, i.e., rows that exist in the first query result but not in the second. EXCEPT removes duplicate rows by default, while EXCEPT ALL retains duplicate rows.

Syntax

select_statement EXCEPT [ ALL ] select_statement;

Parameters

Parameter

Description

EXCEPT

Set difference operation. Returns rows that exist in the left query result but not in the right query result.

ALL

When the ALL keyword is added, duplicate rows are retained. Without ALL, duplicate rows are removed by default.

Precautions

  • Each SELECT statement must return the same number of columns.
  • The data types of corresponding columns must be compatible.
  • Spark 4.0 supports the EXCEPT ALL syntax, which retains duplicate rows.
  • Parentheses can be used to control the precedence of multiple set operations (UNION, INTERSECT, EXCEPT).

Examples

Basic EXCEPT difference (with deduplication):

SELECT * FROM student_1 EXCEPT SELECT * FROM student_2; 

EXCEPT ALL retaining duplicate rows (Spark 4.0):

SELECT * FROM student_1 EXCEPT ALL SELECT * FROM student_2; 

Using parentheses to control precedence (Spark 4.0):

(SELECT * FROM student_1 EXCEPT SELECT * FROM student_2)
   UNION SELECT * FROM student_3;