Seeding Test Data: Making Realistic Fake Rows for Practice

Queries only become interesting when there is data to query. Typing a few rows by hand is fine at first, but sooner or later you want dozens or hundreds of realistic, made-up rows. This is called seeding. Here is how to do it simply and safely.

Level 1: a hand-written seed file

Start with a seed.sql file:

INSERT INTO authors (id, name) VALUES (1, 'Author A'), (2, 'Author B');
INSERT INTO books (title, author_id, year) VALUES
  ('First Book', 1, 2019),
  ('Second Book', 1, 2021),
  ('Third Book', 2, 2020);

Load it with sqlite3 practice.db < seed.sql. Hand-written data is perfect for checking results, because you know exactly what the answer to each query should be.

Level 2: generating rows with SQL

SQLite and PostgreSQL can generate rows with a recursive common table expression:

WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 200)
INSERT INTO readings (sensor, value)
SELECT 'sensor-' || (x % 5), x * 1.5 FROM n;

This inserts 200 rows spread across five sensors. PostgreSQL also has generate_series(1, 200), which is simpler.

Level 3: faker libraries

Libraries such as Faker (available for Python and in similar forms for other languages) produce realistic-looking names, addresses, emails and dates:

from faker import Faker
fake = Faker()
rows = [(fake.name(), fake.email()) for _ in range(100)]
conn.executemany("INSERT INTO members (name, email) VALUES (?, ?)", rows)
conn.commit()

The data is invented, but it has realistic shapes and lengths, which helps you notice layout and validation problems.

Make the data interesting

Good practice data has variety:

IncludeBecause
Some NULLs in optional columnsYou practise IS NULL
Duplicates where allowedGROUP BY and COUNT become meaningful
A parent with no childrenLEFT JOIN results show the difference
Unusual text, such as apostrophes and accentsYou test that placeholders and display work
A wide range of datesRange queries and sorting are realistic

Rules for keeping it safe

  1. Never copy real personal data into practice databases. Use generated or clearly invented values.
  2. Use reserved example domains such as example.com for emails, so nothing reaches a real inbox.
  3. Keep seed scripts in version control so anyone can rebuild the same data.
  4. Make seeding repeatable: delete and recreate, rather than appending again and again.

A tip on checking

Before trusting a query on generated data, run it once on your small hand-written seed where you know the answer. If it is right there, it is probably right on the bigger set.

Where next

For ready-made realistic datasets, see our list of free sample databases, and use the December practice calendar for small daily exercises on seeded data.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site