On this page
  1. DDL & Constraints
  2. Contents
  3. Table Definition & Integrity Constraints
  4. Foreign Keys & Referential Actions
  5. Generated Columns & ALTER TABLE

DDL & Constraints

Prev: sql | Up: sql | Next: DML & Querying
Rel: Normalization & Data Modeling, Schema Migrations & Reliability
Ref: PostgreSQL — Data Definition
Tags: #public #databases #sql #ddl


Contents


Table Definition & Integrity Constraints

Enforce invariants at the database layer so no application bug can write corrupt state:

CREATE TABLE users (
  id          INTEGER PRIMARY KEY,
  email       TEXT NOT NULL UNIQUE,
  role        TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('member', 'admin')),
  created_at  TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Foreign Keys & Referential Actions

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  user_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
  total_cents INTEGER NOT NULL CHECK (total_cents >= 0)
);

Choose ON DELETE intentionally: RESTRICT (safest default), CASCADE (dependent child rows), or SET NULL (optional references). Always index foreign key columns used in joins or parent deletes.


Generated Columns & ALTER TABLE

CREATE TABLE line_items (
  qty         INTEGER NOT NULL,
  unit_cents  INTEGER NOT NULL,
  subtotal    INTEGER GENERATED ALWAYS AS (qty * unit_cents) STORED
);

Linked from

Related notes