Skip to main content
Albero Academy

Table Design & Constraints

Model data well — CREATE TABLE, primary and foreign keys, constraints that guard integrity, and a practical look at normalization.

Chapter 14SQL15 min readBeginner friendly
  • #SQL
  • #Schema
  • #Constraints

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

defining a table
CREATE TABLE students (
id SERIAL PRIMARY KEY, -- auto-incrementing id
name 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:

relationships
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

ConstraintGuarantees
PRIMARY KEYUnique + not null identifier
FOREIGN KEYA valid reference to another table
NOT NULLA value is required
UNIQUENo duplicate values
CHECK (…)A custom rule (e.g. package >= 0)
DEFAULTA 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

evolving a schema
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

  1. 01CREATE TABLE defines columns with types, defaults and constraints.
  2. 02A primary key identifies rows; a foreign key enforces valid references (ON DELETE CASCADE cascades).
  3. 03Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT) let the database guarantee data validity.
  4. 04Enforce rules in the DB, not only in app code — it's the last line of defence.
  5. 05Normalise: store each fact once and link with keys; ALTER TABLE evolves the schema.