C.W.K.
Stream
Lesson 04 of 10 · published

Seeding Data for Development

~10 min · apps, seeding

Level 0Schema Seedling
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Reproducible local data

A seed is a script (SQL or code) that populates a fresh database with reasonable test data. Every developer running the project gets the same starting state — same usernames, same products, same edge cases.

Two patterns

  1. Static SQL seed: a seed.sql with INSERTs. Simple, deterministic, easy to commit to git.
  2. Programmatic seed: a script that generates data (Faker, Mimesis, your model factories). Better for variety and volume; harder to reproduce exactly.

The idempotency win

Make seeds idempotent — re-running shouldn't crash. ON CONFLICT DO NOTHING for fixed-id rows; truncate-then-reload for everything else (in dev only). Anything you wouldn't dare run twice will eventually be run twice.

Code

Idempotent SQL seed·sql
-- seeds/users.sql
INSERT INTO users (id, name, email, role) VALUES
    (1, 'Alice Admin',     'alice@dev.local',  'admin'),
    (2, 'Bob Builder',     'bob@dev.local',    'user'),
    (3, 'Carol Customer',  'carol@dev.local',  'user')
ON CONFLICT (id) DO NOTHING;

INSERT INTO products (id, name, price) VALUES
    (1, 'Widget',  9.99),
    (2, 'Gadget', 24.50),
    (3, 'Gizmo',  99.00)
ON CONFLICT (id) DO NOTHING;
Programmatic seed (Python + Faker)·python
from faker import Faker
fake = Faker()

with conn.cursor() as cur:
    for _ in range(1000):
        cur.execute(
            "INSERT INTO users (name, email) VALUES (%s, %s) ON CONFLICT (email) DO NOTHING",
            (fake.name(), fake.unique.email()),
        )
conn.commit()

External links

Exercise

Write an idempotent seed script for your project that creates a complete starting state. Drop the database, recreate it, run migrations, then the seed. Verify everything works end-to-end.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.