Recursive CTE in SQL
Level 5134 keystrokes
Recursive CTE calls itself to generate sequences or traverse hierarchies.
SQL code
-- WITH RECURSIVE lets the CTE nums refer to itself1WITH RECURSIVE nums AS ( -- Anchor part: the starting row, n = 12 SELECT 1 AS n -- UNION ALL adds the rows produced by the recursive part3 UNION ALL -- Recursive part: build n + 1 from the row created in the previous step4 SELECT n + 15 FROM nums -- Stop condition: once n reaches 10, no new row is made6 WHERE n < 107)-- Use the 10 numbers: each n with its square8SELECT9 n,10 n * n AS square11FROM12 nums-- Sort from 1 to 1013ORDER BY14 n;Output
+----+--------+ | n | square | +----+--------+ | 1 | 1 | | 2 | 4 | | 3 | 9 | | 4 | 16 | | 5 | 25 | | 6 | 36 | | 7 | 49 | | 8 | 64 | | 9 | 81 | | 10 | 100 | +----+--------+ 10 rows in set
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this SQL code and how often they appear.
,× 1;× 1(× 1)× 1*× 1+× 1<× 1