×

sql · level 3 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A builds new rows from its own last rows.

Some answers need repeating: count from 1 to 5, list every date in a month, follow a chain of bosses. A recursive CTE does it. Start with , then write two queries joined by UNION ALL.

The first query is the . It makes the starting rows, here the number 1. The second query reads the rows made last round and makes the next ones, here n + 1.

The WHERE in the second query is the stop condition. When it lets no rows through, the repeating ends. Without it, the query never stops.

WITH RECURSIVE counter(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter ORDER BY n;

counter(n) names the CTE's column, a shortcut that works in any CTE.