// conversion reference

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.

Categoría
Conversion
Returns
setof
In this category
30 of 39

Sintaxis

GENERATE_SERIES(start, stop [, step])

Soporte del motor

MotorSupportNotas
SQL Server Sí SQL Server 2022+, numeric types only; the column is named value
PostgreSQL Sí 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

Ejemplos

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);

Conviene saberlo

  • 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.

// fewer lookups

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.