Arrays and seriesPostgreSQL only

GENERATE_SERIES

Creates rows with a sequence of numbers or points in time.

Syntax

GENERATE_SERIES(<start>, <stop>)
GENERATE_SERIES(<start>, <stop>, <step>)

Generates rows from the start to the end inclusive with the given step: the numbers 1, 2, 3… or dates day by day. No table is needed for it. Most often used to get a complete calendar and show even the days or months when nothing happened in a report.

Data for the examples

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Numbers from 1 to 5
SELECT GENERATE_SERIES(1, 5) AS n;
n
1
2
3
4
5
With a step
SELECT GENERATE_SERIES(0, 100, 25) AS percent;
percent
0
25
50
75
100
Every day of a week
SELECT day::date AS day
FROM GENERATE_SERIES(TIMESTAMP '2026-09-07', TIMESTAMP '2026-09-13', INTERVAL '1 day') AS day;
day
2026-09-07
2026-09-08
2026-09-09
2026-09-10
2026-09-11
2026-09-12
2026-09-13
Orders by month — empty months includedAdvanced
SELECT month_start::date AS month,
COUNT(o.id) AS order_count
FROM GENERATE_SERIES(TIMESTAMP '2026-06-01', TIMESTAMP '2026-09-01', INTERVAL '1 month') AS month_start
LEFT JOIN orders o ON DATE_TRUNC('month', o.created_at) = month_start
GROUP BY month_start
ORDER BY month_start;
monthorder_count
2026-06-010
2026-07-012
2026-08-012
2026-09-011

There were no orders in June, but the month is in the report: LEFT JOIN keeps it, and COUNT(o.id) gives 0.

Watch out

The end is included in the result: GENERATE_SERIES(1, 5) gives 5 rows.

If the start is greater than the end and the step is positive, there are no rows at all. To count backwards, use a negative step: GENERATE_SERIES(5, 1, -1).

For dates, an interval step is required. And if you pass a DATE, the result becomes timestamp with time zone and depends on the time zone — that's why the examples use TIMESTAMP and ::date.

Related functions

Learn more in the course