Sub topic 13
Generating Rows with CONNECT BY LEVEL
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, understand Oracle’s DUAL table, and have seen self-referencing hierarchical queries. Here, CONNECT BY LEVEL generates rows without reading an application table.
The basic pattern
LEVEL is a hierarchical pseudocolumn. It starts at 1 for the root row and increases by one for each generated child row. Because DUAL contains one row, it provides a single starting point.
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 10;The result contains the integers from 1 through 10:
| N |
|---|
| 1 |
Oracle evaluates the CONNECT BY condition for each level. When LEVEL <= 10 becomes false, generation stops.
A normal hierarchical query uses PRIOR to relate a parent row to a child row. This row-generation pattern has no PRIOR relationship because the purpose is to create a sequence. The LEVEL condition controls the sequence length.
Generating dates
Oracle stores a DATE value with day precision and supports arithmetic on dates. Adding one to a date adds one day. The following query generates seven consecutive dates:
SELECT DATE '2026-01-01' + LEVEL - 1 AS calendar_day
FROM dual
CONNECT BY LEVEL <= 7;LEVEL - 1 starts the offset at zero, so the first row is January 1. The last row is January 7.
You can calculate the number of rows from a start and end date:
SELECT DATE '2026-01-01' + LEVEL - 1 AS calendar_day
FROM dual
CONNECT BY LEVEL <=
DATE '2026-01-07' - DATE '2026-01-01' + 1;The + 1 includes both endpoints. Without it, the end date would be omitted.
Generating time intervals
A fraction of a day represents hours. One hour is 1/24 of a day. This query creates 24 hourly timestamps:
SELECT DATE '2026-01-01' + (LEVEL - 1) / 24 AS hour_start
FROM dual
CONNECT BY LEVEL <= 24;Use an explicit ORDER BY when row order matters. Hierarchical output often appears in traversal order, but SQL does not guarantee result order without ORDER BY.
When to use this pattern
CONNECT BY LEVEL is useful for:
- Number sequences for test data or reporting.
- Calendar rows between two dates.
- Hourly or daily time slots.
- Splitting work into a known number of repeated positions.
For complex recursive relationships, use a real hierarchical query or recursive WITH clause instead. CONNECT BY LEVEL is best when one root row and a simple numeric limit are enough.
Exercise
Write a query that returns the numbers 1 through 5 and labels the generated column position.
Show answer
SELECT LEVEL AS position FROM dual CONNECT BY LEVEL <= 5;