Good queries start with good tables. This chapter is about schema design — defining tables, the keys that link them, and the constraints that let the database enforce your rules automatically. A well-designed schema prevents whole classes of bad data.
CREATE TABLE
CREATE TABLE students (id SERIAL PRIMARY KEY, -- auto-incrementing idname VARCHAR(100) NOT NULL,email VARCHAR(150) UNIQUE,package DECIMAL(5,2) DEFAULT 0 CHECK (package >= 0),enrolled DATE,created_at TIMESTAMP DEFAULT NOW());
Primary & foreign keys
A primary key uniquely identifies each row. A foreign key references another table's primary key and the database enforces that the reference is valid:
CREATE TABLE enrolments (id SERIAL PRIMARY KEY,student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE,programme_id INT NOT NULL REFERENCES programmes(id));-- ON DELETE CASCADE: deleting a student removes their enrolments too.
Constraints
| Constraint | Guarantees |
|---|---|
PRIMARY KEY | Unique + not null identifier |
FOREIGN KEY | A valid reference to another table |
NOT NULL | A value is required |
UNIQUE | No duplicate values |
CHECK (…) | A custom rule (e.g. package >= 0) |
DEFAULT | A fallback value |
Normalization
Normalization means organising tables so each fact lives in exactly one place, linked by keys — no duplicated data. If you find yourself copying the same value (a programme name) onto many rows, that value wants its own table. This removes update anomalies (fix a typo once, not in 500 rows).
Altering tables
ALTER TABLE students ADD COLUMN phone VARCHAR(20);ALTER TABLE students ALTER COLUMN email SET NOT NULL;ALTER TABLE students DROP COLUMN temp;ALTER TABLE students ADD CONSTRAINT uq_email UNIQUE (email);
Practice
Design a two-table schema: programmes and students with a programme_id foreign key. Add sensible types, a CHECK on a numeric column, a UNIQUE email, and NOT NULLs. Then ALTER a column in.
Key takeaways
- 01CREATE TABLE defines columns with types, defaults and constraints.
- 02A primary key identifies rows; a foreign key enforces valid references (ON DELETE CASCADE cascades).
- 03Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT) let the database guarantee data validity.
- 04Enforce rules in the DB, not only in app code — it's the last line of defence.
- 05Normalise: store each fact once and link with keys; ALTER TABLE evolves the schema.
