Sub topic 13
Generating rows with CONNECT BY LEVEL
This chapter assumes you can write a basic hierarchical query with START WITH, CONNECT BY and PRIOR, and that you know what the LEVEL pseudocolumn returns. You also need to be comfortable with the DUAL table and with joins. Here you will use CONNECT BY for something other than trees: producing a sequence of rows from nothing.
Why generate rows
Some problems need rows that no table holds. Examples:
- A list of every date in a month, so that days with no sales still appear in a report.
- The numbers 1 to N, to use as an index or a multiplier.
- One row per element of a comma-separated string.
- N copies of a row, where N is stored in a column.
Oracle has no generate_series function in the classic releases. The long-standing idiom is a hierarchical query over DUAL that has no PRIOR in its condition.
How the idiom works
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 10;This returns the numbers 1 through 10. Oracle evaluates it in these steps:
- There is no
START WITH, so every row ofDUALis a root.DUALhas one row, so there is one root, atLEVEL1. - For each row at the current level, Oracle looks for child rows that satisfy the
CONNECT BYcondition. The conditionLEVEL <= 10does not mentionPRIOR, so it does not compare parent and child columns. It depends only on the depth being tested. DUALagain supplies one candidate child per parent, so each level adds exactly one row.- Once
LEVELwould reach 11, the condition is false and the walk stops.
The result is a single chain of ten rows rather than a branching tree.
The last row is level 10 because the condition is checked for each candidate child before it is added.
Generating dates
Date arithmetic in Oracle adds days when you add a number, so a number sequence becomes a date sequence directly.
SELECT DATE '2026-11-01' + LEVEL - 1 AS d
FROM dual
CONNECT BY LEVEL <= 30;When the number of rows depends on a computed boundary, put the whole expression in the condition:
SELECT TRUNC(SYSDATE, 'MM') + LEVEL - 1 AS d
FROM dual
CONNECT BY TRUNC(SYSDATE, 'MM') + LEVEL - 1 <= LAST_DAY(TRUNC(SYSDATE, 'MM'));This returns every day of the current month, whether the month has 28, 29, 30 or 31 days.
Filling gaps in a report
A common use is a left join from a generated calendar to real data, so that days with no activity show a zero. The query below is self-contained, with inline sample data:
WITH sales (sale_date, amount) AS (
SELECT DATE '2026-11-01', 100 FROM dual UNION ALL
SELECT DATE '2026-11-03', 250 FROM dual UNION ALL
SELECT DATE '2026-11-03', 50 FROM dual
),
days AS (
SELECT DATE '2026-11-01' + LEVEL - 1 AS d
FROM dual
CONNECT BY LEVEL <= 5
)
SELECT TO_CHAR(days.d, 'YYYY-MM-DD') AS sale_day,
NVL(SUM(s.amount), 0) AS total
FROM days
LEFT JOIN sales s ON s.sale_date = days.d
GROUP BY days.d
ORDER BY days.d;The result has five rows: 100, 0, 300, 0 and 0. Without the generated days list, the missing dates would simply not appear.
Splitting a delimited string
LEVEL can be used as the occurrence argument of REGEXP_SUBSTR, so that each generated row extracts the next element:
SELECT REGEXP_SUBSTR('red,green,blue', '[^,]+', 1, LEVEL) AS item
FROM dual
CONNECT BY LEVEL <= REGEXP_COUNT('red,green,blue', ',') + 1;The upper bound is the number of delimiters plus one. The pattern [^,]+ skips empty elements, so a string such as a,,c would produce a, c and then a NULL row. If you must keep empty elements, use the pattern ([^,]*)(,|$) with sub-expression 1 as the sixth argument.
The multi-row source trap
The idiom depends on the source having exactly one row. Run it over a table with more rows and the result grows quickly, because every row is a root and every row can be a child of every parent.
SELECT COUNT(*) AS row_count
FROM (
SELECT 1 AS x FROM dual UNION ALL
SELECT 1 FROM dual UNION ALL
SELECT 1 FROM dual
)
CONNECT BY LEVEL <= 3;With three source rows the query returns 39 rows: 3 at level 1, 9 at level 2 and 27 at level 3. For a source of s rows and a limit of n, the count is the sum of s to the power k for k from 1 to n. A 1,000-row table with a limit of 5 would try to build more than 10^15 rows.
Repeating rows by a quantity column
To make each row appear as many times as its qty column says, generate a generous list of numbers once and join with an inequality:
WITH items (item, qty) AS (
SELECT 'bolt', 3 FROM dual UNION ALL
SELECT 'nut', 2 FROM dual
),
nums AS (
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 100
)
SELECT i.item, n.n AS copy_no
FROM items i
JOIN nums n ON n.n <= i.qty
ORDER BY i.item, n.n;This returns three bolt rows and two nut rows. The number list must be at least as large as the biggest quantity, so choose the limit with that in mind.
From Oracle 12c, a lateral join lets the generator refer to the outer row, so no fixed upper limit is needed:
WITH items (item, qty) AS (
SELECT 'bolt', 3 FROM dual UNION ALL
SELECT 'nut', 2 FROM dual
)
SELECT i.item, g.n AS copy_no
FROM items i
CROSS JOIN LATERAL (
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= i.qty
) g
ORDER BY i.item, g.n;Each outer row now gets its own one-row DUAL walk, so the exponential growth does not occur.
Termination and where the condition goes
The CONNECT BY condition is what stops the walk. A WHERE clause cannot do that job, because WHERE filters rows after they have been produced.
A related point: in CONNECT BY LEVEL <= n the value of n can be a bind variable or a subquery result, as long as it is a single value for the walk. That makes the idiom useful for parameterised reports.
Alternatives
The same sequence can be written with recursive subquery factoring, available from Oracle 11g Release 2:
WITH n (x) AS (
SELECT 1 FROM dual
UNION ALL
SELECT x + 1 FROM n WHERE x < 10
)
SELECT x FROM n;The table below compares the options.
| Technique | Strength | Limit |
|---|---|---|
| `CONNECT BY LEVEL` over `DUAL` | Short, widely known, works in old releases | Unsafe on multi-row sources unless isolated |
| Recursive `WITH` | Standard SQL style, clear stopping condition | Needs 11g Release 2 or later, longer to write |
| `CONNECT BY` inside `LATERAL` | Limit can come from the outer row | Needs 12c or later |
| Join to a stored numbers table | Fast and simple for repeated use | You must create and maintain the table |
For very large counts, such as millions of rows, a single CONNECT BY walk can use a lot of memory. A common workaround is to cross join two smaller generators. For example, two lists of 1,000 numbers give a million combinations.
Summary of the rules
- Use
DUALas the source so there is exactly one root. - Leave out
PRIORandSTART WITH. - Put the limit in the
CONNECT BYcondition, never only inWHERE. - Generate numbers in their own query block, then join to them.
Exercise
Write a query that returns the first seven days of 2027, one row per day, with the date in column d and the three-letter weekday abbreviation in column wd.
Show answer
SELECT DATE '2027-01-01' + LEVEL - 1 AS d, TOCHAR(DATE '2027-01-01' + LEVEL - 1, 'DY') AS wd FROM dual CONNECT BY LEVEL <= 7; The walk starts from the single DUAL row, and each level adds one day to the base date. The weekday text depends on the session's NLSDATE_LANGUAGE setting.
Exercise
A four-row table is queried with SELECT COUNT(*) FROM t CONNECT BY LEVEL <= 2. How many rows does the count return, and why?
Show answer
The count is 20. Every one of the 4 rows is a root at level 1, which gives 4 rows. At level 2 each of the 4 parents has 4 children because the condition does not compare parent and child columns, which gives 16 more. The total is 4 + 16 = 20. Running the same idea over DUAL, which has one row, would give only 2.