Back to all posts

Relational Database Schema Design Procedure

For architects and developers taking a relational schema from requirements to its first deployment; each of the seven steps ends in a decision you write down.

On this page

Once rows depend on a schema, every change to the schema becomes a migration. The reasons behind the design get lost too: a year later, nobody can say why a column allows NULL. Design the schema in seven steps, each ending in a decision short enough to write down.

  1. List the questions the application must ask, and mark what the first release leaves out.
  2. Turn each noun into a table and each fact into a column, with a junction table for every many-to-many relationship.
  3. Give every table a primary key, and every relationship a foreign key and a delete rule.
  4. Normalize until each business change updates one row.
  5. Choose the type and the constraints of every column on the engine you deploy to.
  6. Index the foreign keys, then add an index only for a query you can name.
  7. Load sample rows and try to break every rule. Each constraint must refuse the bad row.

A relational schema defines a database's tables, columns, keys and constraints. You design one small schema through all seven steps below. For the normal forms row by row, read the worked example of a relational schema.

Step 1: Write down the questions the database must answer

Start from questions, not tables. A schema is right or wrong only for the questions that it has to answer. The example is a movie review site, and its first release has to return:

  1. the movies in a genre
  2. a movie's average rating
  3. the reviews a user wrote
  4. whether a user already reviewed a movie

For each question, note who writes the data, which values must be unique, and which links are mandatory. The fourth question is also a rule: one review per user and movie. Write down that actors, watchlists and subscriptions belong to a later release.

Decision: a written list of the questions and of what is out of scope. Check every later step against this list.

Step 2: Turn the nouns into tables and columns

Each noun in the questions becomes a table, and each fact about it becomes a column:

TableColumnsOne row is
usersuser_id, email, created_atone account
moviesmovie_id, title, release_yearone movie in the catalog
genresgenre_id, nameone genre, so each name is stored once
movie_genresmovie_id, genre_idone movie in one genre
reviewsreview_id, user_id, movie_id, ratingone user's rating of one movie

A movie has several genres and a genre has several movies, so neither table can hold the link. The link goes into a junction table, movie_genres, with one row for each pair of a movie and a genre. The reviews table links a user to a movie too, and holds a fact of its own, the rating.

Decision: the table list for the first release. Adding a table later is cheap. Removing a table that holds data is expensive.

Step 3: Pick the keys and wire the relationships

Every table needs a primary key that never changes. A surrogate key is a generated number with no business meaning. Prefer one to anything a user can edit. Make the email address a UNIQUE column, not the key. An email address can change. The junction table movie_genres uses the pair movie_id and genre_id as its key.

Each relationship here is one to many. Every foreign key column is NOT NULL, because no child row exists without its parent. Then choose the delete rule: what happens to the child rows when their parent row is deleted. Deleting a user deletes their reviews, and deleting a movie deletes its genre links. That rule is CASCADE. A movie with reviews, or a genre in use, cannot be deleted. That rule is RESTRICT.

The five tables users, reviews, movies, genres and movie_genres, with a line from each parent key to the child's foreign key, labeled one to many and CASCADE or RESTRICT

Without an ON DELETE clause, PostgreSQL, MySQL and SQL Server use NO ACTION, which refuses the delete while child rows exist. Write each rule in an ON DELETE clause anyway. Later, nobody can tell a decision from a default. If foreign keys are new to you, read What Is a Foreign Key? first.

Decision: for each relationship, the cardinality, whether the child is optional, and the delete rule.

Step 4: Normalize until updates stop repeating themselves

Normalization checks one thing: one business change, such as renaming a genre, updates one row. Storing the genres as a list inside movies fails that check.

On the left, movies with a genres column holding Drama, Sci-Fi; on the right, the same data as movie_genres rows and a genres table, where renaming Sci-Fi changes one row

Each normal form removes one way that a fact ends up stored twice:

Normal formWhat it removesExample
1NFlists and repeating groups in one columnthe genres list moves to movie_genres
2NFa column that depends on part of a composite keya genre name on movie_genres would depend on genre_id alone, so it lives in genres
3NFa column that depends on another non-key columna studio_country on movies would depend on studio_name, so it needs a studios table

Decision: third normal form by default. Store a fact twice only for a query you measured, and record which query it was.

Step 5: Choose data types and constraints per engine

The same logical column becomes a different type on each engine:

Logical columnPostgreSQLMySQLSQL ServerOracleSQLite
Surrogate keyBIGINT GENERATED ALWAYS AS IDENTITYBIGINT AUTO_INCREMENTBIGINT IDENTITY(1,1)NUMBER(19) GENERATED AS IDENTITYINTEGER PRIMARY KEY
UUID keyUUIDBINARY(16) or CHAR(36)UNIQUEIDENTIFIERRAW(16)TEXT or BLOB
Short textVARCHAR(n) or TEXTVARCHAR(n)NVARCHAR(n)VARCHAR2(n)TEXT
Boolean flagBOOLEANTINYINT(1)BITBOOLEAN, from 23aiINTEGER 0 or 1
MoneyNUMERIC(19,4)DECIMAL(19,4)DECIMAL(19,4)NUMBER(19,4)INTEGER, in cents
Point in timeTIMESTAMPTZTIMESTAMPDATETIMEOFFSETTIMESTAMP WITH TIME ZONETEXT in ISO-8601

Watch for these engine behaviors:

Set the constraints in the same pass. Use NOT NULL where a value is mandatory, UNIQUE on natural identifiers such as email, and CHECK on ranges. Add a default value only where every new row should get that value. On PostgreSQL 18, the movie review schema is:

CREATE TABLE users (
  user_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      varchar(254) NOT NULL UNIQUE,
  created_at timestamptz  NOT NULL DEFAULT now()
);

CREATE TABLE movies (
  movie_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title        varchar(200) NOT NULL,
  release_year smallint     NOT NULL
);

CREATE TABLE genres (
  genre_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name     varchar(50) NOT NULL UNIQUE
);

CREATE TABLE movie_genres (
  movie_id bigint NOT NULL REFERENCES movies ON DELETE CASCADE,
  genre_id bigint NOT NULL REFERENCES genres ON DELETE RESTRICT,
  PRIMARY KEY (movie_id, genre_id)
);

CREATE TABLE reviews (
  review_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id   bigint   NOT NULL REFERENCES users ON DELETE CASCADE,
  movie_id  bigint   NOT NULL REFERENCES movies ON DELETE RESTRICT,
  rating    smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),
  UNIQUE (user_id, movie_id)
);

UNIQUE (user_id, movie_id) is the one-review rule from step 1. Every statement and result from here on ran on PostgreSQL 18.6. For MySQL syntax, see CREATE TABLE.

Decision: the exact type of every column on the target engine, with a range that the real data cannot outgrow.

Step 6: Decide which indexes earn their cost

Add an index only for a query you can name. An index makes reads faster and every write slower. Start with the foreign keys. PostgreSQL 18 creates no index for a foreign key. Without such an index, each delete of a parent row scans the child table. List the indexes that PostgreSQL did create:

SELECT indexname
FROM pg_indexes
WHERE tablename IN ('reviews', 'movie_genres')
ORDER BY indexname;
indexname
movie_genres_pkey
reviews_pkey
reviews_user_id_movie_id_key

Only the primary keys and the UNIQUE constraint got an index. An index helps a lookup on its leading column, the first column that it lists. So the index on (user_id, movie_id) serves reviews.user_id, and the primary key serves movie_genres.movie_id. No index starts with reviews.movie_id or movie_genres.genre_id. Two questions from step 1 need them: a movie's average rating, and the movies in a genre. Index both columns:

CREATE INDEX reviews_movie_id_idx ON reviews (movie_id);
CREATE INDEX movie_genres_genre_id_idx ON movie_genres (genre_id);

MySQL 8.4 creates the index for a foreign key itself when no usable index exists. SQL Server does not, and Oracle's documentation advises indexing foreign keys as a rule.

After the foreign keys, index a column for a frequent WHERE clause on a large table, or for an ORDER BY whose query plan shows a Sort step. A composite index is an index on several columns, such as (a, b). It helps a filter on a, or on a and b, but not a filter on b alone. Skip columns with few distinct values, tables written far more than read, and guesses. Indexes and Foreign Keys goes further.

Decision: an index for every foreign key column that no index starts with, then nothing until a query plan asks for one. Record the query that each index serves. The next person can then drop an index safely.

Step 7: Prove the design with sample data and real queries

A diagram that looks right proves nothing. Load a few rows:

INSERT INTO users (email) VALUES ('[email protected]'), ('[email protected]');
INSERT INTO movies (title, release_year) VALUES ('Arrival', 2016), ('Heat', 1995);
INSERT INTO genres (name) VALUES ('Drama'), ('Sci-Fi');
INSERT INTO movie_genres VALUES (1, 1), (1, 2), (2, 1);
INSERT INTO reviews (user_id, movie_id, rating) VALUES (1, 1, 5), (2, 1, 4), (2, 2, 3);

Then try to break each rule. Each of these four statements has to fail:

INSERT INTO reviews (user_id, movie_id, rating) VALUES (1, 99, 4);
INSERT INTO reviews (user_id, movie_id, rating) VALUES (1, 1, 2);
INSERT INTO reviews (user_id, movie_id, rating) VALUES (1, 2, 6);
DELETE FROM movies WHERE movie_id = 2;

PostgreSQL refuses all four, in order:

ERROR:  insert or update on table "reviews" violates foreign key constraint "reviews_movie_id_fkey"
DETAIL:  Key (movie_id)=(99) is not present in table "movies".
ERROR:  duplicate key value violates unique constraint "reviews_user_id_movie_id_key"
DETAIL:  Key (user_id, movie_id)=(1, 1) already exists.
ERROR:  new row for relation "reviews" violates check constraint "reviews_rating_check"
DETAIL:  Failing row contains (6, 1, 2, 6).
ERROR:  update or delete on table "movies" violates RESTRICT setting of foreign key constraint "reviews_movie_id_fkey" on table "reviews"
DETAIL:  Key (movie_id)=(2) is referenced from table "reviews".

Movie 99 does not exist, and user 1 has already reviewed movie 1. A rating of 6 is outside the CHECK range. Heat has a review, so RESTRICT refuses to delete the movie. In the CHECK error, the failing row starts with review_id 6. The two failed inserts before this one used up the identity values 4 and 5. If one of these statements succeeds, a constraint is missing.

Test the CASCADE rules the opposite way, with a delete that succeeds and removes the child rows too:

DELETE FROM users WHERE user_id = 2;
SELECT user_id, movie_id, rating FROM reviews;
user_idmovie_idrating
115

User 2 had two reviews, and the delete removed both with the account. Test the other two delete rules the same way. Last, run the questions from step 1 on a realistic number of rows. Read each query plan with EXPLAIN, not only the result.

Decision: no deployment until every constraint has refused a bad row and you have seen every delete rule act.

The pre-launch review checklist

Run this checklist before the schema reaches an environment that holds real data.

CheckFails when
every table has a primary keya junction table was created without one
every relationship has a foreign keya column ending in _id points nowhere
delete rules are explicitON DELETE was left to the engine's default
each fact is stored oncea value that isn't a key, such as a customer's email, sits in two tables
NOT NULL, UNIQUE and CHECK are seta mandatory column allows NULL
types are engine-specifica column is still typed "string" or "number"
every index serves a named querynobody can say which query an index is for
the schema is documentedonly the DDL exists

For the failure patterns behind these checks, read Database Design Mistakes.

Where DbSchema fits in the procedure

In DbSchema, a database design tool, steps 2, 3, 5 and 6 take less work. DbSchema builds the diagram, the keys and the SQL from one model of the schema:

  1. On the Welcome Screen, open the Start New tab, choose Design from Scratch, click PostgreSQL, and press Start Design. DbSchema opens an empty model.
  2. Add the five tables. To create a foreign key, drag the child column onto its parent column, such as reviews.movie_id onto movies.movie_id. In the New Foreign Key dialog, set On Delete to the rule from step 3. On the dialog's Optimizations tab, the option Optimize deletions by indexing the referring column(s) adds the index of step 6.
  3. To change the delete rule later, double-click the foreign key's line on the diagram. The Edit Foreign Key dialog opens.
  4. Press SQL at the bottom of a table dialog. The View SQL Statement window shows the table's CREATE TABLE statement.
The five tables of the movie review site on a DbSchema diagram, with foreign key lines from reviews to users and movies, and from movie_genres to movies and genres
The DbSchema Edit Foreign Key dialog of reviews_movie_id_fkey, with the referring and referred column movie_id and On Delete set to restrict

Offline, DbSchema keeps every change in the model only. Once DbSchema is connected to a database, each change that you confirm with OK runs there at once. A model designed offline reaches the database through schema synchronization, which shows the SQL before running it. In the Community Edition, connect to a local database while you design, and the database keeps each change. Saving the model to a file needs DbSchema Pro.

For the last row of the checklist, DbSchema generates HTML5 documentation with the diagram and every table's columns, keys and comments.

A table in the HTML5 documentation that DbSchema generates: its comment, its columns with data types and constraints, its indexes and its foreign keys

Download DbSchema from https://dbschema.com/download.html, choose Design from Scratch, and draw this example's five tables on a diagram. The free Community Edition covers the diagram and the table and foreign key dialogs. DbSchema Pro adds the saved model file, schema synchronization, and HTML5 documentation for diagrams of more than 12 tables.

Design your schema visually, then generate the SQL

DbSchema reverse-engineers your database, keeps large diagrams readable, and generates DDL for your engine. The Community Edition is free.