A Common Table Expression (CTE) is a temporary result set that is used only within the statement that contains it. A CTE does not store data as a separate object, but returns data as if it were a table. Unlike derived tables, CTEs can reference themselves and can be reused multiple times in the same query. A CTE can be recursive.
Scenarios:
- You can reuse the same CTE multiple times in the same statement without rewriting the same logic multiple times.
- You can use a CTE to simplify recursive queries, such as those used to process hierarchical data.
- You can break a complex query into smaller parts by using a CTE, thus simplifying the query logic.
OceanBase Database supports both recursive and non-recursive CTEs.
CTE syntax
A common table expression is an optional part of the DML statement syntax. It is defined by using the WITH clause. Multiple WITH clauses can be separated by commas. Each WITH clause contains a subquery that generates a result set and associates the result set with a name. The syntax is as follows:
WITH [RECURSIVE]
cte_name [(column_name [, column_name] ...)] AS (subquery)
[, cte_name [(column_name [, column_name] ...)] AS (subquery)] ...
Arguments
Argument |
Description |
|---|---|
[RECURSIVE] |
Optional keyword to specify whether to create a recursive CTE.
|
cte_name |
The name of the CTE, which can be referenced by tables in the WITH clause. |
column_name |
The selected column names that are used to alias the columns in the CTE. This enables you to use more readable column names in the main query. |
AS(subquery) |
The subquery that generates the result set of the CTE. AS must be followed by parentheses. |
If the CTE name is followed by a name list in parentheses, the names in the list are column names. The number of names must be the same as the number of columns in the SELECT statement of the CTE. If no column names are specified, the column names are from the first SELECT list in AS(subquery).
Scenarios supported by the WITH clause
You can use the WITH clause in the following scenarios:
At the beginning of a
SELECTstatement.WITH ... SELECT ...At the beginning of a subquery (including a derived table subquery).
SELECT ... WHERE id IN (WITH ... SELECT ...) ... SELECT * FROM (WITH ... SELECT ...) AS dt ...Immediately before the
SELECTclause in a statement that contains aSELECTstatement.INSERT ... WITH ... SELECT ... REPLACE ... WITH ... SELECT ... CREATE TABLE ... WITH ... SELECT ... CREATE VIEW ... WITH ... SELECT ...
You can use at most one WITH clause at the same level. If multiple WITH clauses are included in the query, separate them with commas.
WITH cte1 AS (...), cte2 AS (...) SELECT ...
The WITH clause can define one or more common table expressions. However, each CTE name must be unique within the WITH clause. The following example is illegal:
WITH cte1 AS (...), cte1 AS (...) SELECT ...
Structure of a recursive CTE
A recursive CTE has the following structure:
If the CTE in the
WITHclause references itself, theWITHclause must start withWITH RECURSIVE. Otherwise, it does not need to start withRECURSIVE.The recursive CTE's subquery consists of two parts that are separated by
UNION [ALL]:SELECT ... -- Returns the initial row set. UNION ALL SELECT ... -- Returns additional row sets.The first
SELECTgenerates one or more initial rows for the CTE and does not reference the CTE name. The secondSELECTgenerates additional rows through recursion by referencing the CTE name in itsFROMclause. The recursion ends when the secondSELECTdoes not generate new rows. Therefore, a recursive CTE consists of a non-recursiveSELECTpart and a recursiveSELECTpart. EachSELECTpart can be composed of multipleSELECTstatements.The column types of the CTE are inferred from the column types of the non-recursive
SELECTpart. By default, all columns can be null. The types of the recursiveSELECTpart are ignored.The rows generated by the recursive part are processed only based on the preceding iteration. If the recursive part contains multiple query blocks, the iterations of the query blocks are scheduled in an unspecified order, and a query block operates on the rows generated by the preceding iteration or by other query blocks after the preceding iteration.
Here is an example:
WITH RECURSIVE cte1 (n) AS
(
SELECT 1 /*Non-recursive part. It retrieves a single row to generate the initial row set.*/
UNION ALL
SELECT n + 2 FROM cte1 WHERE n < 10 /*Recursive part. It generates a new value that is 2 greater than the value of n in the preceding row set. The recursion continues until n is no less than 10.*/
)
SELECT * FROM cte1;
Limitations
The recursive SELECT part of a recursive CTE must meet the following requirements:
It must not contain the following structures:
Aggregate functions such as
SUM()Window functions
GROUP BYORDER BYDISTINCT
It must reference a table only through a subquery in its
FROMclause. It can join the CTE with a table or another CTE. If it uses the CTE in aJOINclause, theLEFT JOINcannot be on the right side of theJOINclause.
The cost estimation displayed in the EXPLAIN statement for a recursive CTE represents the cost of each iteration and can differ significantly from the total cost. The optimizer cannot estimate the number of iterations because it cannot determine when the condition in the WHERE clause becomes False.
- The recursive
SELECTpart cannot contain theUNION [DISTINCT]orLIMITstructure.
Examples
The following example shows how to create a student hierarchy table that contains the IDs, names, and mentors of students to demonstrate the difference between recursive and non-recursive CTEs.
First, create the student hierarchy table and insert some data into it:
obclient> CREATE TABLE student (
student_id INT PRIMARY KEY,
name VARCHAR(100),
mentor_id INT,
FOREIGN KEY (mentor_id) REFERENCES student(student_id)
);
Query OK, 0 rows affected
obclient> INSERT INTO student (student_id, name, mentor_id) VALUES
(1, 'Alice', NULL),
(2, 'Bob', 1),
(3, 'Charlie', 1),
(4, 'David', 2),
(5, 'Eve', 3);
Query OK, 5 rows affected
In this data model, Alice is a top-level student who does not have a mentor. Bob and Charlie are Alice's students. David is Bob's student, and Eve is Charlie's student.
Non-recursive CTE example
A non-recursive CTE does not reference itself. For example, if you want to select all students directly mentored by Alice (i.e., first-level students), you can use the following non-recursive CTE:
WITH Alice_Students AS (
SELECT * FROM student WHERE mentor_id = 1
)
SELECT * FROM Alice_Students;
The execution result is as follows:
+------------+---------+-----------+
| student_id | name | mentor_id |
+------------+---------+-----------+
| 2 | Bob | 1 |
| 3 | Charlie | 1 |
+------------+---------+-----------+
2 rows in set
Recursive CTE example
If you want to find all students directly and indirectly mentored by Alice (i.e., all students at all levels), you must use a recursive CTE. A recursive CTE references itself to query students at the next level.
WITH RECURSIVE Student_Hierarchy AS (
-- Anchor member: Select Alice as the starting point.
SELECT student_id, name, mentor_id FROM student WHERE mentor_id IS NULL
UNION ALL
-- Recursive member: Select direct students of students at the previous level.
SELECT s.student_id, s.name, s.mentor_id
FROM student s
INNER JOIN Student_Hierarchy sh ON s.mentor_id = sh.student_id
)
SELECT * FROM Student_Hierarchy;
This recursive CTE selects Alice as the starting point and then recursively selects direct students of each student until no more students are found.
The execution result is as follows:
+------------+---------+-----------+
| student_id | name | mentor_id |
+------------+---------+-----------+
| 1 | Alice | NULL |
| 3 | Charlie | 1 |
| 2 | Bob | 1 |
| 5 | Eve | 3 |
| 4 | David | 2 |
+------------+---------+-----------+
5 rows in set
In this example, the recursive CTE allows you to traverse the hierarchical structure of students, while the non-recursive CTE can only select students at a fixed level.
