Help Center/ AI DataLake/ Spark reference/ Query Syntax/ Clauses/ Multi-Level Nested Subquery
Updated on 2026-11-06 GMT+08:00

Multi-Level Nested Subquery

Function

A multi-level nested subquery refers to nesting subqueries within subqueries. That is, using another SELECT statement as a data source within the FROM clause of a SELECT statement. This can be nested across multiple levels.

Syntax

SELECT attr_expr FROM (
   SELECT attr_expr FROM (
     SELECT attr_expr FROM ...
   ) [alias]
 ) [alias]; 

LATERAL subquery syntax (supported by Spark 4.0):

SELECT attr_expr FROM table_reference
   LATERAL VIEW OUTER explode(array_col) alias AS col_name;

SELECT attr_expr FROM table_reference,
   LATERAL (SELECT ... FROM ... WHERE ...) AS alias;

Parameters

Parameter

Description

attr_expr

The query column expression, specifying the columns to be returned.

alias

The alias for the subquery. In a nested query, each subquery must be assigned an alias. Otherwise, an error is reported.

LATERAL VIEW

The LATERAL VIEW keyword is used to expand a column in a table into multiple rows. It is often used with table-generating functions such as explode and json_tuple.

LATERAL (subquery)

A LATERAL subquery allows referencing columns from preceding tables in the FROM clause. Newly supported in Spark 4.0.

OUTER

An optional keyword. When the result of a LATERAL VIEW expansion is empty, the original row is retained and the expanded column is set to NULL.

Precautions

  • The table being queried must already exist. Otherwise, an error will occur.
  • In a nested query, an alias must be specified for the subquery. Otherwise, an error is reported.
  • An alias must be defined before it is referenced. It is recommended that aliases be unique.
  • A LATERAL subquery can reference columns from tables that appear before it in the FROM clause.

Examples

Through three levels of subqueries, ultimately return the name field from user_info.

SELECT name 
FROM (
   SELECT name, acc_num FROM (
     SELECT name, acc_num, password FROM (
       SELECT name, acc_num, password, bank_acc FROM user_info
     ) a
   ) b
 ) c; 

LATERAL VIEW example, expanding an array column into multiple rows:

SELECT name, course 
FROM student_info 
LATERAL VIEW OUTER explode(courses) courses AS course; 

LATERAL subquery example (Spark 4.0):

SELECT o.order_id, s.total 
FROM orders o,
   LATERAL (SELECT SUM(amount) AS total FROM order_items i WHERE i.order_id = o.order_id) s;