Schema design and normalization
Model data so it stays correct: keys, constraints and normal forms.
A good schema makes wrong data hard to store. The database can enforce many rules for you, so use constraints instead of trusting application code alone.
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
total NUMERIC(10, 2) NOT NULL CHECK (total >= 0),
status TEXT NOT NULL DEFAULT 'new',
created_at TIMESTAMP NOT NULL
);- PRIMARY KEY: unique and not null, identifies a row.
- FOREIGN KEY (
REFERENCES): the value must exist in the other table, so you cannot create an order for a missing user. - NOT NULL, UNIQUE, CHECK: reject missing, repeated or invalid values.
Normalization
Normalizing means storing each fact once. The usual steps are:
- First normal form: each cell holds one value, with no lists such as "red,green" in a column.
- Second normal form: every non-key column depends on the whole key, not part of it.
- Third normal form: non-key columns depend only on the key, not on each other. A city name does not belong in the orders table if the city is determined by the zip code.
Many-to-many
Students and courses are many-to-many. Model it with a junction table enrollments (student_id, course_id) whose primary key is the pair.
CarefulNever store money in floating point types. Use NUMERIC/DECIMAL, or integers of the smallest unit (cents).
NoteDenormalizing on purpose (copying a value to avoid a join) is sometimes right for reporting speed. Do it knowingly, and keep one table as the source of truth.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.