Skip to content
Visual explainer 8h to learn 6 steps

Build a database for an app (e.g. e-commerce or library)

A repo with schema migrations, seed data, analytics queries, indexes justified by EXPLAIN and a backup script.

By Invicly Tech, , in SQL & PostgreSQL. About 12 minutes to read.

Topic 30 of 30

In short

The build turns the model into a working, documented database repo: versioned migrations, realistic seed data, analytics queries with CTEs and window functions, indexes proven by EXPLAIN, and a tested backup script.

Explained simply

Now the design becomes a real, working database that anyone can rebuild from your repository. Each change to the schema lives in a numbered file called a migration, and running them in order recreates the database exactly.

An empty database cannot teach you much, so you fill it with seed data: thousands of realistic rows made with SQL. Real-looking volume matters, because PostgreSQL chooses how to run a query based on table sizes.

Then you write the queries the business asked for: monthly totals, rankings, trends. Common table expressions (CTEs, the WITH ... AS blocks) break big queries into readable steps, and window functions compute running totals and rankings without losing the individual rows.

Finally you make it production-like: add indexes only where EXPLAIN proves they help, write a backup script and prove it by restoring, and document it all in a README so a reviewer can run everything in a few minutes.

Press Play on a diagram to walk through it one step at a time.

MapCapstone repository layout
shop-db/
  • migrations/
    • 0001_init.sql
    • 0002_indexes.sql
  • seed/
    • seed.sql (thousands of rows)
  • queries/
    • monthly_revenue.sql
    • top_products.sql
    • explain_notes.md
  • scripts/
    • backup.sh
    • restore_test.sh
  • README.md
    • ER diagram
    • How to run
CycleJustifying each index
  1. 1
    Write the query

    A real report from the requirements

  2. 2
    EXPLAIN ANALYZE

    Record plan and time without the index

  3. 3
    Add one index

    Matched to the WHERE and ORDER BY

  4. 4
    Compare plans

    Keep it only if it clearly helps

  5. Back to step 1
FlowRebuild from zero, every time
  1. 1
    Drop database

    Start from nothing

  2. 2
    Run migrations

    0001 to latest, in order

  3. 3
    Load seed

    setseed for repeatable data, then ANALYZE

  4. 4
    Run queries

    Check outputs and EXPLAIN plans

  5. 5
    Backup and restore test

    Row counts must match

In depth

Versioned migrations

A migration is a file that moves the schema from one version to the next: 0001_init.sql, 0002_add_reservations.sql, 0003_indexes.sql. A migration tool records which files have run in a table, so each runs exactly once and in order. Popular choices are Flyway, Liquibase, dbmate and sqitch; for a capstone, even a short shell script that runs each file with psql and records it in a schema_migrations table works.

Rules that keep migrations safe: never edit a file that has already run anywhere, add a new one instead. Wrap each migration in a transaction; PostgreSQL supports transactional DDL, so a failed migration leaves no half-built tables. Commands that cannot run in a transaction, like CREATE INDEX CONCURRENTLY, need their own file and a tool setting that allows it.

Prove reproducibility: in CI or locally, drop the database, run all migrations from zero, then load the seed. If that works, anyone can rebuild your project.

  • psql -v ON_ERROR_STOP=1 makes a script stop at the first error
  • psql -1 runs a whole file in one transaction
  • Keep seed data separate from schema migrations

Realistic seed data with generate_series

generate_series(1, 50000) produces 50,000 rows you can turn into data with random(). Realism matters more than raw size. Real data is skewed: a few books are borrowed far more often than others, and most loans are returned on time. Plans and index choices depend on that shape. You can skew values with a power of random(), for example floor(power(random(), 3) * 5000) + 1 picks low ids much more often.

Make seeds repeatable. Call SELECT setseed(0.42) at the start of the seed script so random() gives the same sequence every time, which keeps EXPLAIN results and example outputs in your README stable.

Load in dependency order (members and books, then copies, then loans), respect your constraints (the one-open-loan-per-copy index will reject bad seed rows, which is a good test), and run ANALYZE afterwards so the planner has fresh statistics.

Analytics with CTEs and window functions

A CTE names a step of a query: WITH monthly AS (SELECT ...) SELECT ... FROM monthly. It reads top to bottom like a recipe. Since PostgreSQL 12, simple CTEs used once are inlined into the main query, so they no longer block optimisation; add MATERIALIZED only when you want a step computed once.

Window functions calculate across related rows while keeping every row. SUM(n) OVER (ORDER BY month) gives a running total. LAG(n) OVER (ORDER BY month) gives last month's value for month-over-month change. ROW_NUMBER() or DENSE_RANK() OVER (PARTITION BY category ORDER BY loans DESC) ranks items inside each group, and a filter on that rank gives "top 3 per category".

Window results cannot be filtered in the same WHERE, because WHERE runs before windows are computed. Wrap the query in a CTE and filter outside it.

FlowTop 3 books per genre, step by step
  1. Step 1
    Join loans to books

    One row per loan with its genre

  2. Step 2
    Group and count

    Loans per book within the year

  3. Step 3
    Rank with a window

    DENSE_RANK per genre by count

  4. Step 4
    Filter in outer query

    WHERE rank <= 3

Indexes justified by EXPLAIN

For each important query, run EXPLAIN (ANALYZE, BUFFERS) and save the output. Look at the node types (Seq Scan, Index Scan, Bitmap Heap Scan), the actual time, the rows estimated versus actual, and the buffers read. Then add one index that matches the query's WHERE, JOIN and ORDER BY columns, rerun, and compare.

Column order in a composite index matters: put equality filters first, then range filters or sort columns. An index on loans(member_id, borrowed_at) serves "loans for member 7, newest first" directly. A partial index such as loans(due_at) WHERE returned_at IS NULL is tiny and perfect for the overdue report.

Keep an index only if it clearly helps a query you actually run. Each index slows inserts and updates and uses disk. Write a short note per index in the repo: the query, the plan before and after, and the timing.

CompareOverdue report before and after a partial index
Before
  • Seq Scan on loans
  • Reads every loan row
  • Filter removes most rows
  • Time grows with history
After
  • Index Scan on a partial index
  • Only open loans are in the index
  • Already ordered by due_at
  • Time stays low as history grows

Backup, restore test and README

pg_dump makes a logical backup of one database. The custom format (-Fc) is compressed and lets pg_restore pick objects, run in parallel with -j, and reorder steps. pg_dumpall --globals-only saves roles, which pg_dump does not include.

A backup only counts when a restore has been tested. The script should create a fresh database, restore into it, and check something real: table row counts match, or a known query returns the same answer. Run it on a schedule or in CI, and keep the backup file name dated so old ones can be pruned.

The README ties everything together: what the database is for, the ER diagram, how to run migrations and seed (ideally one command, such as docker compose up plus make seed), the analytics queries with sample output, the index notes, and how to back up and restore. A reviewer should go from git clone to a working database in under five minutes.

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Write versioned schema migrations~1h 20m
  2. 2
    Create realistic seed data~1h 20m
  3. 3
    Write analytics queries with CTEs and windows~1h 20m
  4. 4
    Add indexes justified by EXPLAIN~1h 20m
  5. 5
    Write a backup and restore script~1h 20m
  6. 6
    Document the schema in a README~1h 20m

Key points

  • Seed enough data that plans differ from a near-empty table.
  • Run migrations from scratch to prove they rebuild the schema.
  • Save before-and-after EXPLAIN output next to each index decision.
  • Test the backup by restoring it into a fresh database.

Key terms

Tap a card to flip it. 0/4 known

Examples

sql
-- seed 50,000 orders spread over a year
INSERT INTO orders (customer_id, status, ordered_at)
SELECT (random() * 999 + 1)::bigint,
       (ARRAY['paid', 'shipped', 'cart'])[1 + floor(random() * 3)::int],
       now() - random() * interval '365 days'
FROM generate_series(1, 50000);

ANALYZE orders;

Realistic volume makes EXPLAIN results meaningful.

Monthly loans with running total and change

The CTE counts loans per month. The outer query adds a running total with SUM OVER, last month's count with LAG, and the percentage change. NULLIF avoids division by zero in an empty month. date_trunc returns the first moment of each month.

sql
WITH monthly AS (
  SELECT date_trunc('month', borrowed_at) AS month, count(*) AS loans
  FROM loans
  WHERE borrowed_at >= now() - interval '12 months'
  GROUP BY 1
)
SELECT month::date,
       loans,
       SUM(loans) OVER (ORDER BY month)  AS running_total,
       LAG(loans) OVER (ORDER BY month)  AS prev_month,
       round(100.0 * (loans - LAG(loans) OVER (ORDER BY month))
             / NULLIF(LAG(loans) OVER (ORDER BY month), 0), 1) AS pct_change
FROM monthly
ORDER BY month;

A backup script that proves itself

The script dumps the library database in custom format with a dated name, restores it into a scratch database, and compares row counts for key tables. If any count differs, it exits with an error, so a scheduler or CI job notices. set -euo pipefail stops on the first failure.

bash
#!/usr/bin/env bash
set -euo pipefail
file="backups/library_$(date +%F).dump"
pg_dump -Fc -d library -f "$file"
dropdb --if-exists library_restore_test
createdb library_restore_test
pg_restore -d library_restore_test -j 4 "$file"
for t in members books copies loans; do
  a=$(psql -tAc "SELECT count(*) FROM $t" library)
  b=$(psql -tAc "SELECT count(*) FROM $t" library_restore_test)
  [ "$a" = "$b" ] || { echo "mismatch in $t: $a vs $b"; exit 1; }
done
echo "backup $file verified"

Quick reference

  • Never edit a migration that has run; add a new numbered file
  • psql -v ON_ERROR_STOP=1 -1 -f file.sql runs one file atomically and stops on error
  • SELECT setseed(0.42); before random() makes seed data repeatable
  • Run ANALYZE after loading seed data so plans use real statistics
  • Window results cannot be filtered in WHERE; wrap in a CTE first
  • EXPLAIN (ANALYZE, BUFFERS) shows real time, row counts and pages read
  • pg_dump -Fc + pg_restore -j 4 for fast, flexible restores; roles need pg_dumpall -g
  • A backup is only proven by a successful restore and a data check

Common mistakes

  • Testing performance with only a handful of rows.
  • Adding indexes without evidence from EXPLAIN.
  • A backup script that has never been used to restore.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A migration that already ran in production has a typo in a column name. What should you do?

Question 2

2Why can you not write WHERE rank <= 3 in the same query that computes rank with a window function?

Question 3

3Which index best serves: open loans ordered by due_at for the overdue report?

Question 4

4What does pg_dump of one database not include?

Question 5

5Why call setseed before generating seed data with random()?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a migration runner in bash that applies every file in migrations/ in order, stopping at the first error.

  2. Exercise 2medium

    Seed 2,000 members, 5,000 books with one or two copies each, and 100,000 loans where popular books are borrowed far more often. Make it repeatable.

  3. Exercise 3hard

    Write the query "top 3 most borrowed books per year" and justify one index for it with EXPLAIN (ANALYZE, BUFFERS) output before and after.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Which migration tool should I use with PostgreSQL?
Flyway and Liquibase are common in Java teams, dbmate and sqitch are simple standalone tools, and frameworks like Django and Rails have their own. Any tool that runs numbered files once and in order is fine for a capstone.
How much seed data is enough?
Enough that the planner's choices change: tens of thousands to a few million rows in the main tables. Realistic skew matters as much as size.
Is pg_dump enough for production backups?
For small databases it is a good start. Larger systems usually add physical backups with point-in-time recovery, using tools like pgBackRest or a managed service's built-in backups.
Should I commit the seed data as a big SQL file?
Commit the script that generates it, not the output. A generator with setseed is small, reviewable and gives the same data every time.
ShareXLinkedInWhatsApp