Designing the schema from features

Intermediate · 11 min

Derive Taskboard's tables from its user stories, then add the constraints that make the database refuse bad data so the API and UI cannot corrupt it.

Before thisSeed data and the dev database workflow

Database Star · 11 min

Designing the schema from features

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Database StarReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Read the nouns in your user stories as candidate tables and the verbs between them as relationships.
  • A one-to-many relationship is a foreign key on the many side, so a task holds project_id and a project holds no task list.
  • Constraints such as NOT NULL, UNIQUE, CHECK and foreign keys make the database the last line of defence against bad data from any layer.
  • Choose what happens on delete deliberately: cascade for owned children, set null for optional links, and restrict for things that must not vanish.
  • Index the columns your screens filter and join on, but add an index when a real query needs it, not for every column.

Start from the stories, not the tables

The mistake in schema design is opening a diagram tool and drawing boxes. Start with the user stories from the planning lesson instead, and underline the nouns:

  • A signed-in user creates a project.
  • A member adds a task to a project.
  • A member moves a task between statuses.
  • A member writes a comment on a task.
  • A member attaches a file to a task.

Nouns that have their own facts and their own lifetime become tables: users, projects, tasks, comments, attachments. A status is just one fact about a task, so it is a column, not a table. The verbs between nouns become relationships. This is the same thinking the system-design roadmap calls normalization and the ER model, applied to a concrete app, and the video below walks through designing a database in general.

Relationships are foreign keys

A foreign key is a column that holds another row’s id. It is how a relational database says “this belongs to that.”

Every Taskboard relationship here is one-to-many. One project has many tasks. One task has many comments. The rule is always the same: the key lives on the many side. A task row stores project_id. The project row stores nothing about its tasks, because you can ask the database for them whenever you like.

Here is the schema I built and ran on Postgres through PGlite 0.5.17:

CREATE TABLE users (
  id serial PRIMARY KEY,
  email text NOT NULL UNIQUE,
  name text NOT NULL
);

CREATE TABLE projects (
  id serial PRIMARY KEY,
  owner_id integer NOT NULL REFERENCES users(id),
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE tasks (
  id serial PRIMARY KEY,
  project_id integer NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
  assignee_id integer REFERENCES users(id) ON DELETE SET NULL,
  title text NOT NULL,
  status text NOT NULL DEFAULT 'todo' CHECK (status IN ('todo','doing','done')),
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX tasks_project_status_idx ON tasks (project_id, status);

CREATE TABLE comments (
  id serial PRIMARY KEY,
  task_id integer NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
  author_id integer NOT NULL REFERENCES users(id),
  body text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE attachments (
  id serial PRIMARY KEY,
  task_id integer NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
  storage_key text NOT NULL UNIQUE,
  filename text NOT NULL,
  content_type text NOT NULL,
  size_bytes integer NOT NULL CHECK (size_bytes > 0),
  created_at timestamptz NOT NULL DEFAULT now()
);

Two small choices are worth a note. timestamptz stores a moment in time and handles time zones for you. (The backend roadmap’s time, timezones and locale-aware data explains why plain timestamps cause trouble.) And attachments stores a storage_key, a pointer to a file held elsewhere, not the file’s bytes. The uploads lesson at the end of this group explains why.

Constraints: the database as the last line of defence

Your API validates its input. So does the form. Neither is the only way data gets into a database. A migration, a script, a bug in a new endpoint, or a hurried fix over a SQL console can all write rows directly. Constraints reject bad data no matter who sends it. I tried each one against the schema above:

bad status    -> violates check constraint "tasks_status_check"
orphan task   -> violates foreign key constraint "tasks_project_id_fkey"
zero size     -> violates check constraint "attachments_size_bytes_check"
dup email     -> violates unique constraint "users_email_key"

Four bad inserts, four refusals. Each constraint is a rule about the data’s meaning that the database itself now enforces:

  • NOT NULL: this fact is required.
  • UNIQUE: no two rows may share this value, so two accounts can’t share an email.
  • CHECK: the value must satisfy a condition, such as a legal status or a positive size.
  • REFERENCES: the row it points at must exist, so no task can belong to a project that isn’t there.

This is a seam, the first of several in this group. The client, the API and the database each know the rule about statuses. The cheapest place to be certain is the database, because every writer goes through it.

Decide what happens on delete

A foreign key forces a question: when the referenced row goes away, what happens to the rows that point at it? Postgres makes you choose, and the right choice depends on the relationship.

Relationship Rule used Why
Task to project ON DELETE CASCADE A task has no meaning without its project
Comment to task ON DELETE CASCADE Comments belong to the task
Task assignee to user ON DELETE SET NULL The task should survive; it just becomes unassigned
Project owner to user none (restrict) You must decide what happens to a user’s projects first

I checked two of these. After deleting a task, its comments were gone (the count read zero). And deleting a user who still owned a project failed with violates foreign key constraint "projects_owner_id_fkey". That second behaviour is the default and it is a good one. It stops you from deleting something other things depend on without thinking.

Cascade is convenient and dangerous. It means one delete removes a whole tree of rows silently. Use it for data that is truly owned, and be wary of it on anything that touches money or audit trails.

Indexes: add the ones your screens need

tasks_project_status_idx is there because the project page asks “tasks in this project, grouped by status”, which means filtering on both columns. A query without a helpful index must scan every task. The system-design roadmap explains indexes in depth.

Don’t index every column in advance. Each index slows writes and takes space. A better habit: design for the queries the screens run, then check the plan. I asked Postgres to EXPLAIN the “todo tasks in project 1, newest first” query and it reported Index Scan using tasks_project_status_idx. With 100 rows, a planner may choose either way, so treat that as confirming the index is usable, not as a speed measurement.

What a schema is not

It is not final. You will add columns, and later lessons will, for example, add things for authentication. Getting the relationships and the constraints right now is what makes those later changes safe, and zero-downtime deploys and schema changes covers how to change it while people use the app.

It is also not your API. The table layout is internal. What the API returns is a separate decision, which the next group takes up.

What the video covers

Database Star’s “How to Design a Database” is about eleven minutes and was published in May 2022. Its description is mostly promotion for the channel’s design guides and a framework course, so the content has to be inferred from the title: a general walk through database design. I could not read a transcript or chapters, and it is not specific to web apps or to Postgres. Use it for the process of going from a description to tables, and use the schema above for what the constraints look like in practice.

Where this fits

You have tables, relationships and rules. The next step is reading and writing them from TypeScript without losing the types: typed queries with an ORM in a feature.

Check yourself

  1. 01How do you turn 'a member comments on a task' into schema?

    Comment is a noun and becomes a table. It belongs to a task and to an author, so it holds a task_id and an author_id as foreign keys.

  2. 02Where does the foreign key go in a one-to-many relationship between projects and tasks?

    On the many side. Each task row stores a project_id, and the project row stores nothing about its tasks.

  3. 03Why put a CHECK constraint on task status when the API already validates it?

    Because the API is not the only writer. A script, a migration or a bug can write directly, and the database constraint rejects a bad value regardless of who sent it.

  4. 04What happens to a task's comments when the task is deleted with ON DELETE CASCADE?

    They are deleted too. I checked that comments for a deleted task were gone afterwards.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark