skip to content

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.

rows from =
per-day.sql
  1. 1SELECT occurred_at::date AS day, count(*) AS purchases
  2. 2FROM events
  3. 3WHERE kind = 'purchase' AND occurred_at >= '2026-04-01' AND occurred_at < '2026-05-01'
  4. 4GROUP BY 1
  5. 5ORDER BY 1;
29 rows · 30 days · purchases

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.

real output, postgres 18.6 (PGlite 0.5.12) · generate-series
april 2026, purchases per day. with the events only, GROUP BY makes 29 rows, and the 14th is just absent. with a calendar first, every day has a row, and the 14th shows its 0.

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:

sqlempty db
SELECT n FROM generate_series(1, 10, 3) AS n ORDER BY n;
output, from postgres 18.6
SELECT 4
nint4
1
4
7
10
(4 rows)

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:

sqlempty db
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;
output, from postgres 18.6
SELECT 4
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
(4 rows)

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:

sqlempty db
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;
output, from postgres 18.6
SELECT 3
dtimestamptztyperegtypedaydate
2026-04-13 00:00:00+00timestamp with time zone2026-04-13
2026-04-14 00:00:00+00timestamp with time zone2026-04-14
2026-04-15 00:00:00+00timestamp with time zone2026-04-15
(3 rows)

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:

sqldb=events
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;
output, from postgres 18.6
SELECT 5
daydatepurchasesint8
2026-04-1217
2026-04-1324
2026-04-140
2026-04-1522
2026-04-1616
(5 rows)

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.kind is NULL). ON decides what matches; WHERE decides what survives. (outer joins has that rule.)
  • count(e.id), not count(*). look:
count =
query.sql
  1. 1SELECT d::date AS day, count(*) AS purchases
  2. 2FROM generate_series(date '2026-04-12', date '2026-04-16', interval '1 day') AS d
  3. 3LEFT JOIN events AS e
  4. 4 ON e.occurred_at::date = d::date AND e.kind = 'purchase'
  5. 5GROUP BY d
  6. 6ORDER BY d;
the result for count(*)
daydatepurchasesint8
2026-04-1217
2026-04-1324
2026-04-141
2026-04-1522
2026-04-1616
(5 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · generate-series
switch the count. 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.
predict the output
sql
-- 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 6
idint4daydate
32025-07-01
32025-07-02
112025-07-01
112025-07-02
112025-07-03
112025-07-04
(6 rows)

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:

sqlempty db
SELECT round(random()::numeric, 4) AS today, round(random()::numeric, 4) AS also_today;
output, from postgres 18.6
SELECT 1
todaynumericalso_todaynumeric
0.49000.9731
(1 row)

(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":

sqlempty db
SELECT setseed(0.42);
SELECT round(random()::numeric, 4) AS r FROM generate_series(1, 3) ORDER BY 1;
output, from postgres 18.6
#1 · SELECT 1
setseedvoid
''
(1 row)
#2 · SELECT 3
rnumeric
0.3625
0.7429
0.9366
(3 rows)

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

sqlempty db
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;
output, from postgres 18.6
SELECT 5
iint4pick_0_to_99int8devicetext
122web
274web
379web
415android
540android
(5 rows)

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:

0 to 20306 orders
20 to 40149 orders
40 to 60104 orders
60 to 8078 orders
80 to 10073 orders
100 to 12059 orders
120 to 14054 orders
140 to 16061 orders
160 to 18054 orders
180 to 20062 orders
1,000 fake order totals, 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.