brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: generate_series fills a PostgreSQL table with test rows in one INSERT

Postgresql
~/tips/tip-postgresql-generate-series-test-data

CREATE TABLE readings (id int, sensor int, taken_at timestamptz, value numeric);

Creates thousands of realistic test rows with one statement to try an index or a query.

To see whether an index helps, a table with ten rows tells you nothing. generate_series makes a big table in one statement.

CREATE TABLE readings (id int, sensor int, taken_at timestamptz, value numeric);
INSERT INTO readings
SELECT g, g % 50, now() - g * interval '1 minute', round((random() * 30)::numeric, 1)
FROM generate_series(1, 100000) AS g;

generate_series(1, 100000) returns the numbers 1 to 100000 as rows, and the SELECT turns each number into a row of test data. Here g % 50 spreads the readings over 50 sensors, each row is one minute older than the one before, and random() fills in a value.

It also counts in time steps, which is great for reports with no gaps:

SELECT day::date FROM generate_series('2026-01-01'::date, '2026-01-31', interval '1 day') AS day;

Join your data against that list with a LEFT JOIN and days without sales show up as zero instead of disappearing.

Run ANALYZE readings; after a big insert before you test plans, or the planner works with old statistics. Also, real data is rarely this even. Uniform test data can make an index look better or worse than it will be in production, so I’d treat the timings as a rough guide. And mind the size: a few million rows is quick, but a stray extra zero fills a small disk.

Further reading: Set returning functions

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link