generate_series and calendars
rows from nothing: date spines, filling gaps with zeros, and fake data that's the same every run.
- address
- everything.analytics.generate_series
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 11 of 11
- reading time
- 8 min
generate_series(start, stop, step) is a function that returns rows: numbers, timestamps, or (with a cast) dates. it's how you make rows that aren't in any table.
its best trick is the date spine: generate every day first, then LEFT JOIN the data to it, so a day with no data still gets a row (and a 0, if you count the right thing). and with a hash of the row number instead of random(), it makes fake data that comes out the same every run.
the picture
you know how a "purchases per day" chart quietly skips the days nobody bought anything, and the line just connects the day before to the day after as if nothing happened? GROUP BY can only make a row for a day that has rows. a day with nothing has no row to group.
think of a wall calendar. you don't wait for something to happen before you print a page for the day: the calendar has every day already, and you write the counts in. the empty days stay on the wall, with nothing (or a 0) written in them.
- 1SELECT occurred_at::date AS day, count(*) AS purchases
- 2FROM events
- 3WHERE kind = 'purchase' AND occurred_at >= '2026-04-01' AND occurred_at < '2026-05-01'
- 4GROUP BY 1
- 5ORDER BY 1;
GROUP BY the day: one row per day that has purchases. 29 rows for a 30-day month, and nothing says which one is missing.
the events table really has nothing on 2026-04-14. a chart drawn from the first query would show a smooth line through it. one drawn from the second shows a hole in the business, which is the true story.
rows from nothing
generate_series lives in FROM, like a table, and hands back one row per value:
SELECT n FROM generate_series(1, 10, 3) AS n ORDER BY n;| nint4 |
|---|
| 1 |
| 4 |
| 7 |
| 10 |
1, 4, 7, 10: start, step, and it stops at the last value that doesn't pass stop. the step is optional for numbers (default 1) and required for timestamps, where it's an interval:
SELECT t
FROM generate_series(timestamptz '2026-03-28 00:00+00',
timestamptz '2026-03-29 12:00+00',
interval '12 hours') AS t
ORDER BY t;| ttimestamptz |
|---|
| 2026-03-28 00:00:00+00 |
| 2026-03-28 12:00:00+00 |
| 2026-03-29 00:00:00+00 |
| 2026-03-29 12:00:00+00 |
there's no date version. generate_series(date, date, interval) quietly turns the dates into timestamps (with time zone, here), so cast back with ::date if you want dates:
SELECT d, pg_typeof(d) AS type, d::date AS day
FROM generate_series(date '2026-04-13', date '2026-04-15', interval '1 day') AS d
ORDER BY d;| dtimestamptz | typeregtype | daydate |
|---|---|---|
| 2026-04-13 00:00:00+00 | timestamp with time zone | 2026-04-13 |
| 2026-04-14 00:00:00+00 | timestamp with time zone | 2026-04-14 |
| 2026-04-15 00:00:00+00 | timestamp with time zone | 2026-04-15 |
the date spine
the calendar is the left side of a LEFT JOIN, so every day survives whether or not any event matches. the events join in where they can:
SELECT d::date AS day, count(e.id) AS purchases
FROM generate_series(date '2026-04-12', date '2026-04-16', interval '1 day') AS d
LEFT JOIN events AS e
ON e.occurred_at::date = d::date AND e.kind = 'purchase'
GROUP BY d
ORDER BY d;| daydate | purchasesint8 |
|---|---|
| 2026-04-12 | 17 |
| 2026-04-13 | 24 |
| 2026-04-14 | 0 |
| 2026-04-15 | 22 |
| 2026-04-16 | 16 |
the 14th is back, with 0. two details carry the whole thing:
- the kind filter is in ON, not WHERE. in WHERE it would run after the join and throw away the 14th's padded row (its
e.kindis NULL). ON decides what matches; WHERE decides what survives. (outer joins has that rule.) - count(e.id), not count(*). look:
- 1SELECT d::date AS day, count(*) AS purchases
- 2FROM generate_series(date '2026-04-12', date '2026-04-16', interval '1 day') AS d
- 3LEFT JOIN events AS e
- 4 ON e.occurred_at::date = d::date AND e.kind = 'purchase'
- 5GROUP BY d
- 6ORDER BY d;
| daydate | purchasesint8 |
|---|---|
| 2026-04-12 | 17 |
| 2026-04-13 | 24 |
| 2026-04-14 | 1 |
| 2026-04-15 | 22 |
| 2026-04-16 | 16 |
count(*) counts rows, and the LEFT JOIN made one row for the 14th: the calendar day, padded with NULLs. so the empty day counts 1.
count(*) counts rows, and the LEFT JOIN made one row for the empty day: the calendar day padded with NULLs. so the 14th, with no purchases, says 1. count(e.id) skips NULLs and says 0.-- the 14th has no events
SELECT d::date, count(*)
FROM generate_series(date '2026-04-14', date '2026-04-14', interval '1 day') AS d
LEFT JOIN events AS e ON e.occurred_at::date = d::date
GROUP BY d;the same spine makes lag honest: once every day has a row, "the previous row" really is yesterday, and a moving average by ROWS really covers the days it says.
series per row
a set-returning function in FROM can use columns from tables to its left: it's lateral without the keyword. every order gets its own series of days, from ordering to shipping:
SELECT o.id, d::date AS day
FROM orders AS o
CROSS JOIN generate_series(o.ordered_at::date, o.shipped_at::date, interval '1 day') AS d
WHERE o.id IN (1, 3, 11)
ORDER BY o.id, day;| idint4 | daydate |
|---|---|
| 3 | 2025-07-01 |
| 3 | 2025-07-02 |
| 11 | 2025-07-01 |
| 11 | 2025-07-02 |
| 11 | 2025-07-03 |
| 11 | 2025-07-04 |
order 3 spans two calendar days, order 11 four. order 1 isn't there at all: it was cancelled, so its shipped_at is NULL, a series with a NULL end is empty, and the CROSS JOIN drops the order.
fake data that's the same every run
need 1,000 orders to test a query? generate_series gives you the rows; you still need values. random() gives different ones every run:
SELECT round(random()::numeric, 4) AS today, round(random()::numeric, 4) AS also_today;| todaynumeric | also_todaynumeric |
|---|---|
| 0.4900 | 0.9731 |
(this page marks that block volatile: its golden can't be compared, only its shape.) two ways to make it repeatable.
seed it. setseed() fixes random()'s sequence for the rest of the session, so the same script gives the same numbers. on the same major version, that is: postgres 15 changed the algorithm, and its release notes warn that results differ from earlier versions "even for the same seed value":
SELECT setseed(0.42);
SELECT round(random()::numeric, 4) AS r FROM generate_series(1, 3) ORDER BY 1;| setseedvoid |
|---|
| '' |
| rnumeric |
|---|
| 0.3625 |
| 0.7429 |
| 0.9366 |
hash it. better: compute each value from the row number with a hash, so any row can be recomputed on its own, in any order, with no session state. this is how every dataset on this site is built (datasets/*/data.sql):
SELECT i,
(hashint4(i)::bigint + 2147483648) % 100 AS pick_0_to_99,
(ARRAY['ios', 'android', 'web'])[1 + (hashint4(i * 7)::bigint + 2147483648) % 3] AS device
FROM generate_series(1, 5) AS i
ORDER BY i;| iint4 | pick_0_to_99int8 | devicetext |
|---|---|---|
| 1 | 22 | web |
| 2 | 74 | web |
| 3 | 79 | web |
| 4 | 15 | android |
| 5 | 40 | android |
the + 2147483648 moves hashint4's result (any int4, negative too) into 0 to 4,294,967,295 before the modulo; abs() would overflow on the one value with no positive twin. squaring a uniform value skews it toward small, which is roughly what real order totals look like:
200 × u² with u from hashint4, in buckets of 20. the same bars on every run, on every machine.keylines
- generate_series makes rows from nothing: numbers, timestamps, dates (via a cast).
- a date spine LEFT JOINed to the data gives every day a row, empty ones included.
- count(col), not count(*), and filters on the data side in ON, not WHERE.
- in FROM it's lateral: a series per row of the table to its left.
- for fake data, hash the row number. random() needs setseed, and differs across versions.