Brightlane's data pipeline assigns sequential batch identifiers to processing jobs. Each identifier is one greater than the previous, starting at 1.
Write a query to return a sequence of batch identifiers from 1 through 5, with each value appearing as a separate row.
Output:
- Five rows, with one column,
job_id, containing the integers1through5in ascending order.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
WITH RECURSIVE
batch AS (
SELECT
1 AS job_id
UNION ALL
SELECT
job_id + 1
FROM
batch
WHERE
job_id < 5
)
SELECT
job_id
FROM
batch The shape
The anchor emits the seed value 1, and the recursive member adds one to the previous row and keeps going while the running value stays below the limit. WITH RECURSIVE is what lets the second SELECT reference the CTE batch by name from inside its own definition.
Clause by clause
- The anchor seeds the sequence:
SELECT 1 AS job_idOne row, one column. This is the first row of batch, and the only row that exists before any recursion runs.
- The recursive member extends the sequence by one step at a time:
UNION ALL
SELECT job_id + 1 FROM batch WHERE job_id < 5Each pass reads the rows produced by the previous pass, adds 1 to job_id, and keeps only the new rows whose source value is below 5. Pass one reads the anchor's 1 and emits 2. Pass two reads 2 and emits 3. The chain continues until the recursive member's WHERE filter drops every candidate, which happens once the source row carries 5: 5 < 5 is false, no row is produced, and the recursion stops.
- The final
SELECTreads the accumulated result:
SELECT job_id FROM batchbatch now contains five rows carrying 1 through 5, which is exactly the sequence the prompt asks for.
The trap
The termination condition lives in the recursive member, not the final SELECT. WHERE job_id < 5 runs against the rows the previous pass produced; once that filter excludes every candidate, the recursion ends. Without the filter, the recursive member would keep adding rows forever, since there is no other condition to stop it. Every WITH RECURSIVE that emits a counted sequence needs a stop condition tied to a value that changes each pass.
You practiced WITH RECURSIVE with an anchor and a UNION ALL step — the simplest recursive CTE shape: emit a base value, then add one and continue while the count stays under a limit.