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

WHERE

Function

The WHERE clause is used to specify filter conditions, returning only the rows that satisfy the conditions. Spark 4.0 enhances the subquery capabilities within WHERE, supporting LATERAL subqueries and correlated subqueries.

Syntax

SELECT [ ALL | DISTINCT ] projectItem [, ...] FROM table_reference [, ...]
   WHERE boolean_expression 

Where boolean_expression can include subqueries:

{ expression operator ( subquery )
   | [ NOT ] EXISTS ( subquery )
   | expression [ NOT ] IN ( subquery | value [, ...] ) }

Parameters

Parameter

Description

ALL

Returns all rows, including duplicate rows. This is the default option.

DISTINCT

Removes duplicate rows from the result set.

boolean_expression

The filter condition expression, which evaluates to a boolean value.

operator

A comparison operator, including =, !=, <, >, <=, >=, etc.

IN / NOT IN

Determines if a value is in the subquery result or value list. When using a subquery, the subquery must return a single column.

EXISTS / NOT EXISTS

Determines if the subquery returns any rows. EXISTS is true when the subquery returns at least one row. The subquery can reference columns from the outer query (correlated subquery).

Precautions

  • The table being queried must already exist. Otherwise, an error will occur.
  • When using IN or NOT IN, the subquery must return a single column.
  • When using EXISTS or NOT EXISTS, the subquery can reference columns from the outer query to form a correlated subquery.

Examples

Basic condition filtering:

SELECT name, score FROM student WHERE score > 90; 

Subquery as a filter condition:

SELECT name FROM student_info
   WHERE courseId = (SELECT courseId FROM course_info WHERE courseName = 'Biology'); 

Using an IN subquery:

SELECT name FROM student_info
   WHERE courseId IN (SELECT courseId FROM course_info WHERE credits > 3); 

Using an EXISTS correlated subquery:

SELECT name FROM student_info s
   WHERE EXISTS (SELECT 1 FROM course_info c WHERE c.courseId = s.courseId AND c.courseName = 'Biology'); 

Using NOT EXISTS:

SELECT name FROM student_info s
   WHERE NOT EXISTS (SELECT 1 FROM course_info c WHERE c.courseId = s.courseId);