For the complete documentation index, see llms.txt. This page is also available as Markdown.

WITH

Complete WITH clause reference: WITH [RECURSIVE] AS (SELECT...) syntax, recursive CTE support, CYCLE...RESTRICT cycle detection, and max_recursive_iterations.

Syntax

WITH [RECURSIVE] table_reference [(columns_list)] AS (
  SELECT ...
) [CYCLE cycle_column_list RESTRICT]
[, table_reference [(columns_list)] AS (
  SELECT ...
) [CYCLE cycle_column_list RESTRICT]] ...
SELECT ...

Description

The WITH keyword signifies a Common Table Expression (CTE). It allows you to refer to a subquery expression many times in a query, as if having a temporary table that only exists for the duration of a query.

There are two kinds of CTEs:

You can use table_reference as any normal table in the external SELECT part. You can also use WITH in subqueries, as well as with EXPLAIN and SELECT.

A single WITH clause can define several CTEs, separated by commas. Each CTE must have a unique name within the clause. A CTE can refer to any CTE defined before it in the same clause. Without the RECURSIVE keyword, a CTE can't refer to a CTE defined after it; with RECURSIVE, the CTEs of the clause can refer to one another in any order. The RECURSIVE keyword is written once, after WITH, and applies to the whole clause.

Poorly-formed recursive CTEs can in theory cause infinite loops. The max_recursive_iterations system variable limits the number of recursions.

CYCLE ... RESTRICT

The CYCLE clause enables CTE cycle detection, avoiding excessive or infinite loops, MariaDB supports a relaxed, non-standard grammar. The SQL Standard permits a CYCLE clause, as follows:

where all clauses are mandatory. MariaDB does not support this, but permits a non-standard relaxed grammar, as follows:

With the use of CYCLE ... RESTRICT it makes no difference whether the CTE uses UNION ALL or UNION DISTINCT anymore. UNION ALL means "all rows, but without cycles", which is exactly what the CYCLE clause enables. And UNION DISTINCT means all rows should be different, which, again, is what will happen — as uniqueness is enforced over a subset of columns, complete rows will automatically all be different.

Examples

Below is an example with the WITH at the top level:

The example below uses WITH in a subquery:

The example below defines two CTEs in one WITH clause. The second CTE, b, refers to the first, a:

Below is an example of a Recursive CTE:

Consider the following structure and data:

Given the above, the following query would theoretically result in an infinite loop due to the last record in t1 (note that max_recursive_iterations is set to 10 for the purposes of this example, to avoid the excessive number of cycles):

However, the CYCLE ... RESTRICT clause can overcome this:

See Also

This page is licensed: CC BY-SA / Gnu FDL

spinner

Last updated

Was this helpful?