Generate Test Data in Postgres, MySQL and SQLite (Pure SQL)
The fastest way to get a realistic table is to copy production and delete the parts you do not need. It is also the way personal data ends up in a repository. Generating rows is the other path: you want volume, foreign keys that hold, and values you can show to someone who should not see customers.
This page is copy-paste SQL to generate dummy data for Postgres, then the same idea in MySQL 8 and SQLite. No extension, no script runtime. The inserts were run on PostgreSQL 16.15, MySQL 8.0.46, and SQLite 3.45.1. Where a limit got in the way, the limit is the one that server shipped with.
If the bug only happens with one real customer’s history, do not generate. Take a filtered, masked copy. That workflow is pg_dump where clause.
When to generate, and when to copy
Generate when:
- You are testing a query plan, an index, or a pagination bug, and any plausible rows will do.
- The dataset will be committed, demoed, or shared.
- Production is huge and the behaviour shows up as soon as a table has a million rows of the right shape.
Copy a slice when:
- The bug is a particular combination of statuses, dates, and missing children that you have not understood well enough to fake.
- You need the real distribution, not a uniform one, and you can mask it.
A generated set that is “random” in every column is a poor stand-in for production. Real tables have skew: most users have a few orders, a few users have thousands, many columns are NULL, status values are not evenly split. The sections below put that skew in the SQL on purpose. Uniform random() is the starting point, not the goal.
PostgreSQL: generate_series and random()
generate_series returns a set of numbers or timestamps. Insert from it.
CREATE TYPE order_state AS ENUM ('review', 'complete', 'shipped');
CREATE TABLE people (
id integer PRIMARY KEY,
email text NOT NULL,
created_at date NOT NULL,
status order_state NOT NULL,
nickname text
);
INSERT INTO people (id, email, created_at, status, nickname)
SELECT
g,
'user' || g || '@example.test',
DATE '2024-01-01' + (floor(random() * 400))::int,
(ARRAY['review','complete','shipped']::order_state[])[1 + floor(random() * 3)::int],
CASE WHEN random() < 0.1 THEN NULL ELSE 'n' || g END
FROM generate_series(1, 3000) AS g;
These statements were run. The insert wrote 3000 rows. About a tenth of nickname was NULL (286 in that run). created_at landed between 1 January 2024 and early February 2025, which is the 400-day window. status used only the three labels in the array, which matters because an enum rejects anything else. Building those labels is covered in postgres enum add value.
random() returns a new double in [0, 1) on every call. It is not seeded in this statement, so two runs differ. For a test that must be repeatable, derive the value from g instead:
SELECT g, DATE '2024-01-01' + (g % 400)
FROM generate_series(1, 3000) AS g;
setseed(0.5) exists if you want random() to repeat inside a session. Call it once before the insert. Do not call it in the middle of a statement and expect a stable plan.
Numbers, dates, enums, emails
Emails need a domain you control, or a reserved one. example.test is a reserved name, so a bug that sends mail does not hit a real domain. Do not generate @gmail.com. A unique index on email will fail the insert if two rows share an address. Including g in the local part makes that impossible.
Dates: add an integer to a date, as above. For timestamps, add an interval:
SELECT TIMESTAMP '2024-01-01' + (g || ' minutes')::interval
FROM generate_series(1, 1000) AS g;
Enums and check constraints: pick from a list that is legal. floor(random() * 3)::int is 0, 1, or 2. Adding 1 makes a 1-based array index. If you write floor(random() * 3)::int as the index you will sometimes ask for element 0, and a PostgreSQL array returns NULL for that. The 1 + is load-bearing.
Integers with a skew, so a few accounts look huge and most look small:
SELECT CASE
WHEN g % 100 = 0 THEN g * 50
ELSE g % 20
END AS order_count
FROM generate_series(1, 1000) AS g;
One percent of the ids, the ones divisible by 100, get a large number. The rest stay small. A query plan for “top customers” looks completely different on this column than on g % 20 alone. That is usually the point of the exercise.
A lot of rows, quickly
For tens or hundreds of thousands of rows, INSERT ... SELECT generate_series(...) is already fine. COPY is faster still, and an UNLOGGED table skips WAL if you can afford to lose the table on a crash. This was run on PostgreSQL 16.15: 100,000 rows into an unlogged table, through COPY, finished in 60 ms. That is one observation on one small virtual machine, not a sizing number.
CREATE UNLOGGED TABLE bulk (
id int,
email text
);
UNLOGGED is for scratch space. It is empty after a crash, it is not replicated by streaming replication, and you should not use it for a database you mean to keep. For a logged table, drop the indexes, load, and recreate the indexes. Building an index once is cheaper than maintaining it on every inserted row.
A series of a million is the same statement with a larger bound. If you are about to do that on a laptop, check disk and the destination. Generating into production “just to see” is how a test table becomes an incident. Point the session at a database you can drop.
generate_series of timestamps is also the way to make a row per day:
SELECT d::date
FROM generate_series(DATE '2024-01-01', DATE '2024-12-31', INTERVAL '1 day') AS d;
That one is 366 rows in 2024. It does not need random() at all.
MySQL: recursive CTEs
MySQL 8 has recursive common table expressions and does not have generate_series. The series is a CTE that starts at 1 and adds 1 until it reaches the bound. The WITH manual describes the shape. This insert was run and produced 5,000 users:
CREATE TABLE users (
id int PRIMARY KEY,
email varchar(255) NOT NULL,
created_at datetime NOT NULL,
status varchar(32) NOT NULL
);
SET cte_max_recursion_depth = 100000;
INSERT INTO users (id, email, created_at, status)
WITH RECURSIVE seq AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM seq WHERE n < 5000
)
SELECT
n,
CONCAT('user', n, '@example.test'),
TIMESTAMP('2024-01-01') + INTERVAL FLOOR(RAND() * 400) DAY,
ELT(1 + FLOOR(RAND() * 3), 'pending', 'paid', 'shipped')
FROM seq;
@@cte_max_recursion_depth defaults to 1000 on MySQL 8.0.46. A series of 5,000 without the SET hits that ceiling. Raise it for the session, not globally, and only as high as the insert needs. ELT picks a string by 1-based position. FLOOR(RAND() * 3) is 0, 1, or 2, so the 1 + keeps the index inside the list. The same off-by-one as PostgreSQL, in a different function.
RAND() is a new value per call and is not stable across runs. For a repeatable set, use n MOD 400 instead of RAND().
Children that reference those users, also run, 800 rows, zero orphans:
CREATE TABLE orders (
id int PRIMARY KEY,
user_id int NOT NULL,
total_cents int NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id)
);
INSERT INTO orders (id, user_id, total_cents)
WITH RECURSIVE seq AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM seq WHERE n < 800
)
SELECT n, 1 + (n % 5000), 100 + (n % 50) * 25
FROM seq;
1 + (n % 5000) is a user id that exists, as long as you loaded users 1 through 5000 first. The modulo wraps. It does not produce a uniform “some users have no orders” distribution. To leave a gap, use 1 + (n % 4000) against 5000 parents. Users 4001 and up then have no orders, which is the more realistic report.
Do not insert the children in the same statement as the parents unless you have written it carefully. A foreign key checked mid-statement can fail depending on the engine and the order the optimizer picks. Two statements, parent file then child file, are easier to restart.
SQLite: recursive CTEs and randomblob
SQLite’s recursive CTE is the same idea. WITH in the SQLite docs is the reference. This built 2,000 users on SQLite 3.45.1, and a later probe built a series of 100,000 on the same build:
CREATE TABLE users (
id integer PRIMARY KEY,
email text NOT NULL,
created text NOT NULL
);
WITH RECURSIVE seq(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM seq WHERE n < 2000
)
INSERT INTO users (id, email, created)
SELECT
n,
'user' || n || '@example.test',
date('2024-01-01', printf('+%d day', abs(random()) % 400))
FROM seq;
date('2024-01-01', '+3 day') is SQLite’s date arithmetic. printf builds the modifier. abs(random()) matters because random() is signed and a negative modifier walks backwards. % 400 after abs keeps it in range. randomblob(8) is the right tool for an opaque token:
SELECT hex(randomblob(8));
That returned 16 hex characters on the test. It is not a password scheme. It is a unique-looking fixture value.
SQLite does not impose a compile-time ceiling on recursive CTE depth. Bound the statement with WHERE or LIMIT, as the 2,000-row query does. A longer series costs memory and time. The message too many levels of trigger recursion belongs to SQLITE_MAX_TRIGGER_DEPTH (limits), which is a trigger limit, not a CTE limit. The 100,000-row series succeeded on Ubuntu’s 3.45.1 package.
Foreign keys in SQLite are off until you ask:
PRAGMA foreign_keys = ON;
Turn that on before the child insert, or you will not find out that user_id dangles. The 500-row child insert used 1 + ((n - 1) % 2000) and the orphan count was 0 with foreign keys enforced.
random() in SQLite is not random() in PostgreSQL. PostgreSQL’s is a float in [0, 1). SQLite’s is a signed 64-bit integer. Copying a Postgres expression into a SQLite file produces nonsense, or an error, rather than a quiet equivalent. Use the snippets for the engine you are seeding.
Keeping foreign keys valid
The reliable pattern is arithmetic, not “pick a random parent” in a subquery per row. A subquery that selects a random id per child is correct and slow, and it is harder to rerun. Modulo against a parent population you just loaded is correct, fast, and obvious in review:
-- parents: ids 1..N already loaded
-- child N is parent ((n - 1) % parent_count) + 1
Load in dependency order. Countries, then customers, then orders, then line items. A many-to-many needs both sides first and the junction table last.
Prefer integer surrogate keys in fixtures. A child id can be 1 + ((n - 1) % parent_count), which is the form that was loaded and checked for orphans. UUID primary keys need an assignment you can still explain in review. Tests can use integers unless the bug is about the identifier format itself.
A foreign key that is ON DELETE CASCADE will surprise you when a later test deletes a parent. Either the cascade is what you are testing, or you should delete children first. Generated data does not remove the need to know the constraints. Dump them (\d in psql, SHOW CREATE TABLE in MySQL, .schema in the SQLite shell) and read the foreign keys before you write the generator.
Making the data realistic
A few changes, all of them expressions you already have:
- Nulls.
CASE WHEN g % 10 = 0 THEN NULL ELSE ... ENDis stable.random() < 0.1is not. Use the stable form in shared fixtures so a test can select “the rows where nickname is null” and find some. - Skew. Most rows get a small number.
g % 100 = 0gets a large one. Status lists should not be uniform if production is 90 percentpaid. Repeatpaidin the array, or map ranges ofgonto labels:g % 10 = 0is the rare status, everything else is the common one. - Duplicates where production has them. Names collide. Emails should not, if the column is unique. Generate collisions on purpose in the column that allows them, and nowhere else.
- Boundaries. Include one row on the minimum date, one on the maximum, one with a zero amount, one with a long string. Bugs live on those rows. A thousand middle-of-the-road rows will not find them.
- Time zones. Store UTC in the fixture and convert in the query you are testing. A generated “local” timestamp with no offset is how a test passes in winter and fails in summer.
Look at a sample of 20 rows before you load a million. If you cannot tell what a row is supposed to be, the generator is not done.
Tools outside SQL
SQL is the right default because it runs wherever the database runs, including a CI job with no extra packages. When the values need to look like real addresses, product names, or paragraphs, a data faker in the application language is a better writer. Faker-style libraries exist for most languages. They belong in the test suite, and their output should still be loaded parent-first.
Hosted generators will build a CSV for you. That is useful once, for a demo. It is a poor place to keep the definition of your fixtures, because the next person cannot see it in review. Download the file, check it in if it is small and contains nothing real, or throw it away and keep the SQL.
Some desktop clients can fill a table for you. The trade is the same as any client feature: faster for an interactive session, invisible to the test suite. Keep the reproducible set in SQL. Use the client when you are exploring.
MoleDB has a Generate test data action for any table you can edit. Point it at a scratch database. The rows are written in that database. Generated data for a scratch database never needs to leave your Mac.
The clients themselves, and which of them suit a Postgres-heavy workflow on a Mac, are compared in best Postgres client for Mac.
Whatever you use, point it at a database you can drop. The generator is not careful. You are.
FAQ
How do I generate test data for a database?
Insert rows from a number series. PostgreSQL has generate_series. MySQL 8 and SQLite build the same series with a recursive CTE, then insert from it. Give each column an expression: an email derived from the number, a date inside a range, a status from a short list. Load parents before children so foreign keys hold. Masked copies of production are a different job from data you invented.
How do you generate test data for automation?
Keep the generator as SQL in the repository, with a fixed seed where the engine allows one, and run it against an empty schema in the test setup. Assert counts and a couple of known rows, not the full table. For a test that must not depend on random draws, use the series number itself instead of random(). Regenerate from empty rather than appending, or the test database grows a new copy of the data on every run.
What is the best way to generate test data?
Use generated data when you need volume, shape, or a demo you can publish. Copy a masked slice of production when the bug depends on a real history. The best set is the smallest one that still has valid foreign keys, a few nulls, and a skewed distribution if your production data is skewed. A million identical rows only tests how fast you can insert a million identical rows.
How do I generate dummy data in MySQL?
MySQL 8 has no generate_series. Build the numbers with a recursive common table expression and insert from it. The default cte_max_recursion_depth on MySQL 8.0.46 is 1000, so a series longer than that errors until you raise the session value. Then insert parents, then children whose foreign key is a number modulo the parent count, so every child points at a real parent.


