Relational Database Schema: Definition and Worked Example
For developers who write SQL and are designing the tables of a new application; normalization and foreign keys are explained where they appear.
On this page
You have a list of requirements and an empty database, and each noun in the list could become a table, a column, or nothing. A relational database schema records what you decide: the tables, their columns, the keys that link the tables, and the constraints that limit the values of each column. The database enforces the schema. For example, it refuses to store a review of a movie that doesn't exist.
Below, you design one small schema from four requirements. You normalize its tables to third normal form, add the keys, and end with a script that runs on PostgreSQL, MySQL and SQLite.
What a relational schema contains
A schema describes five kinds of things:
- tables, one for each kind of thing that the database stores
- columns, each with a data type
- a primary key in each table, which identifies each row
- foreign keys, which link a row to a row in another table
- constraints such as NOT NULL, UNIQUE and CHECK, which limit the values of a column
The schema defines the tables. The rows in them at one moment are called the instance, and the instance changes with every INSERT, UPDATE and DELETE. The schema changes when you run a migration, a script that alters the tables.
Here, schema means the design. In PostgreSQL, a schema is also a named group of tables inside one database, such as the schema public. In MySQL, CREATE SCHEMA is a synonym for CREATE DATABASE.
The movie review example
The example schema stores the data of a small movie review site. The site has four requirements:
Users sign up with a username and an email address.
The catalog lists movies, each with a title and a release year.
A movie belongs to one or more genres.
A user can review a movie once: a rating from 1 to 5, and an optional comment.
Users, movies and reviews each become a table, because the site stores many of each. Each fact about them, such as a movie's title, becomes a column. Suppose the first draft comes from a spreadsheet of reviews, with the user's name on every row:
users (user_id, username, email)
movies (movie_id, title, release_year, genres)
reviews (review_id, user_id, username, movie_id, rating, comment)
A review links a user to a movie. A review also has a rating, a comment and its own key, so reviews get a table of their own. For now, the movies table keeps the genres in one column. Normalization moves them to a table of their own.
Normalization from 1NF to 3NF
Normalization stores each fact in one place. For example, each username is stored in one row. Normalization goes in steps called normal forms, and each one removes one kind of repeated fact.
First normal form
The draft movies table holds a list in its genres column:
| movie_id | title | release_year | genres |
|---|---|---|---|
| 1 | The Matrix | 1999 | Action, Sci-Fi |
| 2 | Alien | 1979 | Horror, Sci-Fi |
To find every Sci-Fi movie, you have to search inside a string. No constraint can check a value that sits inside a longer one. First normal form (1NF) allows one value per cell, so each movie gets one row per genre:
| movie_id | title | release_year | genre |
|---|---|---|---|
| 1 | The Matrix | 1999 | Action |
| 1 | The Matrix | 1999 | Sci-Fi |
| 2 | Alien | 1979 | Horror |
| 2 | Alien | 1979 | Sci-Fi |
The key of this table is movie_id and genre together. Neither column identifies a row alone.
Second normal form
The title and the year now repeat for every genre of a movie. Both depend on movie_id alone: one movie_id always has the same title and year. But movie_id is only part of the key.
Second normal form (2NF) removes a column that depends on only part of the key: you split the table in two. The movies table keeps one row per movie, with its title and year. A new movie_genres table keeps one row per movie and genre:
| movie_id | genre |
|---|---|
| 1 | Action |
| 1 | Sci-Fi |
| 2 | Horror |
| 2 | Sci-Fi |
Third normal form
The draft reviews table repeats the username:
| review_id | user_id | username | movie_id | rating | comment |
|---|---|---|---|---|---|
| 1 | 1 | alice | 1 | 5 | Still holds up |
| 2 | 2 | ben | 1 | 4 | NULL |
| 3 | 2 | ben | 2 | 5 | Scary |
The username describes the user, not the review: one user_id always has the same username. But user_id is not the key of reviews. To rename ben, you have to update every review he wrote. A missed row leaves one user with two names.
Third normal form (3NF) removes this repeat: you drop the username column from reviews and keep only user_id. The users table holds each name once:
| user_id | username | |
|---|---|---|
| 1 | alice | [email protected] |
| 2 | ben | [email protected] |
Stop at 3NF for a schema that an application writes to. Denormalization copies a fact back into a second table. The copy speeds up some reads, and every write then has to update both copies.
Denormalize only for a slow query that you have measured. You can add a copy later, on purpose. Removing duplicates from live data later takes a migration.
Keys and relationships
Each table needs a primary key, and each link between two tables needs a foreign key.
Primary keys
The users, movies and reviews tables each get a number as their key. A username or an email address can change. If one of them were the key, every review that points at the user would have to change too. A number that means nothing never changes.
The movie_genres table has no such number. Its key is the pair of columns. That key also stops one genre from being added to a movie twice.
Junction tables
The movie_genres table still repeats each genre's name. That repeat still fits 3NF, because the genre is part of the key.
But a typo such as Sci-fi creates a new genre, and renaming a genre means updating one row per movie. A genres table stores each name once:
| genre_id | name |
|---|---|
| 1 | Action |
| 2 | Horror |
| 3 | Sci-Fi |
The movie_genres table then keeps only the two keys:
| movie_id | genre_id |
|---|---|
| 1 | 1 |
| 1 | 3 |
| 2 | 2 |
| 2 | 3 |
The movie_genres table is now a junction table, a table that links the rows of two other tables. A movie has several genres, and a genre has several movies. A relational database can't store this many-to-many relationship in a column of movies or of genres. The junction table splits it into two one-to-many relationships, one to movies and one to genres.
Foreign keys and ON DELETE
Every foreign key column is NOT NULL, so a review always has a user and a movie. The row that holds the foreign key is the child, and the row that it points at is the parent. Each foreign key also says what the database does with the child rows when the parent row is deleted:
| Foreign key | Points at | ON DELETE | Effect of deleting the parent |
|---|---|---|---|
| reviews.user_id | users | CASCADE | the user's reviews go too |
| reviews.movie_id | movies | CASCADE | the movie's reviews go too |
| movie_genres.movie_id | movies | CASCADE | the movie's genre rows go too |
| movie_genres.genre_id | genres | RESTRICT | the delete fails while a movie has the genre |
Use CASCADE where a child row means nothing without its parent. Use RESTRICT where a parent row has to stay while any child row points at it.
From the design to SQL
So far, the design names no database engine: it is a logical design. The physical design picks data types and indexes for one engine. Changing a type or a key after the tables hold data takes a migration.
The finished schema has five tables and four foreign keys:
The entity relationship diagram guide explains this notation. The script below creates users, movies and genres before the two tables that point at them. A foreign key can only reference a table that exists. The script runs unchanged on PostgreSQL 18, MySQL 9.1 and SQLite 3.50:
CREATE TABLE users (
user_id int PRIMARY KEY,
username varchar(50) NOT NULL UNIQUE,
email varchar(255) NOT NULL UNIQUE
);
CREATE TABLE movies (
movie_id int PRIMARY KEY,
title varchar(200) NOT NULL,
release_year smallint NOT NULL
);
CREATE TABLE genres (
genre_id int PRIMARY KEY,
name varchar(50) NOT NULL UNIQUE
);
CREATE TABLE movie_genres (
movie_id int NOT NULL,
genre_id int NOT NULL,
PRIMARY KEY (movie_id, genre_id),
FOREIGN KEY (movie_id) REFERENCES movies (movie_id) ON DELETE CASCADE,
FOREIGN KEY (genre_id) REFERENCES genres (genre_id) ON DELETE RESTRICT
);
CREATE TABLE reviews (
review_id int PRIMARY KEY,
user_id int NOT NULL,
movie_id int NOT NULL,
rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment varchar(500),
UNIQUE (user_id, movie_id),
FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE,
FOREIGN KEY (movie_id) REFERENCES movies (movie_id) ON DELETE CASCADE
);
CREATE INDEX movie_genres_genre_id ON movie_genres (genre_id);
CREATE INDEX reviews_movie_id ON reviews (movie_id);
UNIQUE (user_id, movie_id) is the requirement "once" written in SQL. The two CREATE INDEX statements cover the foreign key columns that come second in a key: genre_id in movie_genres and movie_id in reviews. The reason is under "Where the engines differ", below.
These INSERT statements load the rows of the normalization steps:
INSERT INTO users VALUES
(1, 'alice', '[email protected]'),
(2, 'ben', '[email protected]');
INSERT INTO movies VALUES
(1, 'The Matrix', 1999),
(2, 'Alien', 1979);
INSERT INTO genres VALUES
(1, 'Action'),
(2, 'Horror'),
(3, 'Sci-Fi');
INSERT INTO movie_genres VALUES
(1, 1), (1, 3),
(2, 2), (2, 3);
INSERT INTO reviews VALUES
(1, 1, 1, 5, 'Still holds up'),
(2, 2, 1, 4, NULL),
(3, 2, 2, 5, 'Scary');
A query that lists the movies of each genre goes through the junction table:
SELECT g.name AS genre, m.title
FROM genres g
JOIN movie_genres mg ON mg.genre_id = g.genre_id
JOIN movies m ON m.movie_id = mg.movie_id
ORDER BY g.name, m.title;
| genre | title |
|---|---|
| Action | The Matrix |
| Horror | Alien |
| Sci-Fi | Alien |
| Sci-Fi | The Matrix |
Sci-Fi shows twice, once for each of its two rows in movie_genres. Its name is stored once, in genres, so renaming it changes one row.
What the constraints refuse
Each statement below breaks one rule of the schema, and the database refuses it:
INSERT INTO reviews VALUES (4, 1, 99, 3, NULL);
INSERT INTO reviews VALUES (5, 1, 1, 2, 'Second try');
INSERT INTO reviews VALUES (6, 1, 2, 7, NULL);
DELETE FROM genres WHERE name = 'Sci-Fi';
PostgreSQL 18 names the broken constraint in each error (DETAIL lines left out):
ERROR: insert or update on table "reviews" violates foreign key constraint "reviews_movie_id_fkey"
ERROR: duplicate key value violates unique constraint "reviews_user_id_movie_id_key"
ERROR: new row for relation "reviews" violates check constraint "reviews_rating_check"
ERROR: update or delete on table "genres" violates RESTRICT setting of foreign key constraint "movie_genres_genre_id_fkey" on table "movie_genres"
Movie 99 doesn't exist. User alice has already reviewed movie 1. A rating of 7 is out of range. Two movies still have the genre Sci-Fi.
MySQL 9.1 refuses the same four statements with its own messages. SQLite refuses all four too, once its foreign key checks are on (see the next section).
Deleting a movie is allowed, and CASCADE removes the movie's child rows:
DELETE FROM movies WHERE title = 'Alien';
SELECT review_id, user_id, movie_id, rating
FROM reviews
ORDER BY review_id;
| review_id | user_id | movie_id | rating |
|---|---|---|---|
| 1 | 1 | 1 | 5 |
| 2 | 2 | 1 | 4 |
Review 3, ben's review of Alien, was deleted with the movie. Alien's rows in movie_genres were deleted too:
SELECT movie_id, genre_id
FROM movie_genres
ORDER BY movie_id, genre_id;
| movie_id | genre_id |
|---|---|
| 1 | 1 |
| 1 | 3 |
Where the engines differ
The three engines treat the script differently:
- SQLite checks foreign keys only on a connection that has run
PRAGMA foreign_keys = ON;, as its foreign key documentation says. Without the PRAGMA, SQLite 3.50 stored the review of movie 99, deleted Sci-Fi, and kept ben's review of Alien after Alien was deleted. - PostgreSQL and SQLite create no index for a foreign key column. MySQL's InnoDB creates one when no index starts with the column, as its foreign key documentation says. Without an index on movie_genres.genre_id, PostgreSQL has to scan movie_genres for each genre you delete.
The script sets each id by hand. In an application, the database generates the ids, and each engine declares the key column in its own way:
| Engine | Generated key column |
|---|---|
| PostgreSQL 18 | user_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY |
| MySQL 9.1 | user_id int AUTO_INCREMENT PRIMARY KEY |
| SQLite 3.50 | user_id INTEGER PRIMARY KEY |
Draw the schema in DbSchema
DbSchema draws a schema as a diagram from a live database. Run the script above in a database, such as a SQLite file, and connect DbSchema to it.
Choose File → New Model, pick the database, and tick the schema in the Reverse Engineer the Database dialog. DbSchema reads the five tables and draws each foreign key as a line.
To add the next table in DbSchema, choose Table → Create Table in the toolbar and add its columns, as the tables documentation shows. Drag a child column onto its parent column to create a foreign key, and set On Delete in the dialog that opens. For a foreign key that exists, double-click its line to open the Edit Foreign Key dialog.
While DbSchema is connected, DbSchema runs each change in the database as soon as you press OK. To keep the changes in DbSchema's model only, choose Database → Offline (connect later). Schema synchronization then compares the model with the database and applies the difference as SQL.
Download DbSchema at https://dbschema.com/download.html, connect it to the database where you ran the script, and compare its diagram with the one above. Connecting, reverse-engineering and the diagram are in the free Community Edition. Saving the model to a file and synchronizing it with a database need DbSchema Pro.
Design your schema before you build it
DbSchema connects to 100+ SQL and NoSQL databases, reverse-engineers the schema, and lets you edit it as an interactive diagram. Community Edition is free.