SQL reference (MySQL and MariaDB dialects)

WITH (common table expressions)

Non-recursive and recursive common table expressions in SELECT, INSERT, UPDATE, DELETE and CREATE TABLE ... AS.

WITH names a query so that the statement after it can use it like a table.

Syntax#

SQL
WITH [RECURSIVE] cte_name [(col_name, ...)] AS (query_expression)
    [, cte_name [(col_name, ...)] AS (query_expression)] ...
    statement

statement:
    SELECT ... | INSERT ... | UPDATE ... | DELETE ... | CREATE TABLE ... AS SELECT ...

Arguments#

NameMeaningDefault
RECURSIVEThe CTE may refer to itself. The query is seed UNION [ALL] recursive_part.off
(col_name, ...)Names for the columns. The count must match (error 1353 otherwise).names of the query

Remarks#

  • A CTE is read as a derived table with its name. A later CTE may use an earlier one. The same CTE may be used twice in a query.
  • UNION ALL in a recursive CTE keeps every row; UNION stops when a round adds no new row. A recursive CTE runs at most 1000 rounds (MySQL's cte_max_recursion_depth).
  • A CTE in front of DELETE or UPDATE can be used in the subqueries of the statement.
  • CREATE TABLE t AS WITH w AS (...) SELECT ... and CREATE TABLE t AS SELECT inside a WITH are accepted.
  • Privileges: SELECT on the tables the CTEs read.

Examples#

Example:

SQL
WITH c1 AS (SELECT 1 AS a), c2 AS (SELECT a + 1 AS b FROM c1)
SELECT * FROM c1, c2;

WITH RECURSIVE n (v) AS (SELECT 1 UNION ALL SELECT v + 1 FROM n WHERE v < 10)
SELECT SUM(v), COUNT(*) FROM n;

WITH RECURSIVE tree AS (
  SELECT id, boss, 1 AS lvl FROM e WHERE boss IS NULL
  UNION ALL
  SELECT e.id, e.boss, tree.lvl + 1 FROM e JOIN tree ON e.boss = tree.id)
SELECT * FROM tree ORDER BY id;

WITH x AS (SELECT id FROM e WHERE sal < 50)
DELETE FROM e WHERE id IN (SELECT id FROM x);

See also#