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

INTERSECT

Function

INTERSECT returns the intersection of the results of multiple queries, i.e., rows that exist in all query results. INTERSECT removes duplicate rows by default, while INTERSECT ALL retains duplicate rows.

Syntax

select_statement INTERSECT [ ALL ] select_statement;

Parameters

Parameter

Description

INTERSECT

Set intersection operation. Returns rows that exist in both the left and right query results.

ALL

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

Precautions

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

Examples

Basic INTERSECT intersection (with deduplication):

SELECT * FROM student_1 INTERSECT SELECT * FROM student_2; 

INTERSECT ALL retaining duplicate rows (Spark 4.0):

SELECT * FROM student_1 INTERSECT ALL SELECT * FROM student_2; 

Using parentheses to control precedence (Spark 4.0):

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