SQL GENERATE_SERIES function
FROM generate_series(1, 5) returns five rows from nothing. Calendars, gap-filling joins and test data all start from a generated sequence like this.
- Категория
- Conversion
- Returns
setof- In this category
- 30 of 39
Синтаксис
GENERATE_SERIES(start, stop [, step])
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | SQL Server 2022+, numeric types only; the column is named value |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Not built in | no equivalent; recursive CTEs |
| SQLite | Different name or syntax | an extension built into the sqlite3 shell, not the core library |
| Oracle | Not built in | no equivalent; CONNECT BY LEVEL or a recursive CTE |
Примеры
PostgreSQL
SELECT * FROM generate_series(1, 5);
PostgreSQL
SELECT d::date AS day
FROM generate_series(DATE '2026-01-01', DATE '2026-01-07',
INTERVAL '1 day') d;
MySQL
WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 5) SELECT * FROM seq;
SQL Server
SELECT DATEADD(day, value, '2026-01-01') AS day FROM GENERATE_SERIES(0, 6);
Полезно знать
- Counting down differs: PostgreSQL's generate_series(5, 1) returns zero rows unless you pass -1 as the step, while SQL Server's GENERATE_SERIES(5, 1) counts down by itself. A step of 0 is an error on both.
- Dates are PostgreSQL-only: generate_series(DATE '2026-01-01', DATE '2026-01-07', INTERVAL '1 day') returns timestamps, so cast to date in the SELECT. SQL Server rejects date arguments; generate integers and add them with DATEADD.
- MySQL and Oracle build sequences with recursive CTEs instead; the shape changes but the calendar-join technique is identical.
Questions about GENERATE_SERIES
How do I fill calendar gaps?
Generate the date range with generate_series and LEFT JOIN the facts onto it: FROM generate_series(...) d LEFT JOIN sales s ON s.day = d::date. Missing days appear with NULLs instead of vanishing.
Does SQL Server have this?
Yes, from SQL Server 2022, for numbers only. Older versions use a numbers table or a recursive CTE, and the CTE needs OPTION (MAXRECURSION 0) past 100 rows.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Add N business days to a date in SQL Snippet
- Count business days between two dates in SQL Snippet
- Detect missing days in date data Snippet
- List missing values in an id sequence Snippet
- Fill gaps with a calendar spine Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.