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

Reuse Subquery

Function

A common table expression (CTE) defines a named temporary result set using a WITH ... AS statement. This result set can be reused in different parts of a query, avoiding repeated computation of the same subquery, thereby improving query performance and readability.

Syntax

Single subquery:

WITH cte_name AS (
     SELECT ...
     FROM table_name
     WHERE ...
 )
 SELECT ...
 FROM cte_name
 WHERE ...; 

Multiple subqueries:

WITH cte_name1 AS (
     SELECT ...
     FROM table_name
     WHERE ...
 ), 
cte_name2 AS (
     SELECT ...
     FROM table_name
     WHERE ...
 )
 SELECT ...
 FROM cte_name1, cte_name2
 WHERE ...; 

Parameters

Parameter

Description

cte_name

A user-defined name for the subquery. It must be unique within the same WITH statement.

table_name

The name of the table on which the subquery command is executed. The table must already exist.

WITH

The keyword for defining a CTE, followed by one or more named subqueries.

RECURSIVE

The keyword for a recursive CTE, allowing the CTE to reference itself to implement a recursive query.

AS

The keyword used to assign a name to the subquery.

Precautions

  • The table being queried must already exist. Otherwise, an error will occur.
  • Multiple CTEs are separated by commas (,).
  • CTE definitions must precede the main query.
  • A CTE is only valid within the SELECT statement in which it is defined and cannot be used across different queries.
  • A recursive CTE must consist of an anchor query and a recursive query, connected by UNION ALL.

Examples

  • Example 1: Define a subquery sales_data based on the sales table to query products with a sales amount greater than 100, and then query all data from this subquery.
    WITH sales_data AS ( 
      SELECT product_name, sales_amount
      FROM sales
      WHERE sales_amount > 100
    )
    SELECT * FROM sales_data; 
  • Example 2: Define subqueries sales_data1 and sales_data2 based on the sales table. sales_data1 queries products with a sales amount greater than 100, and sales_data2 queries products with a sales amount less than 20. Finally, combine the data from both subqueries.
    WITH sales_data1 AS (
       SELECT product_name, sales_amount
       FROM sales
       WHERE sales_amount > 100
    ),
    sales_data2 AS (
       SELECT product_name, sales_amount
       FROM sales
       WHERE sales_amount < 20
    ) 
    SELECT * FROM sales_data1 
    UNION ALL
    SELECT * FROM sales_data2;