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#
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#
| Name | Meaning | Default |
|---|---|---|
RECURSIVE | The 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 ALLin a recursive CTE keeps every row;UNIONstops when a round adds no new row. A recursive CTE runs at most 1000 rounds (MySQL'scte_max_recursion_depth).- A CTE in front of
DELETEorUPDATEcan be used in the subqueries of the statement. CREATE TABLE t AS WITH w AS (...) SELECT ...andCREATE TABLE t AS SELECTinside aWITHare accepted.- Privileges:
SELECTon the tables the CTEs read.
Examples#
Example:
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);