TechLead
Lesson 4 of 10
5 min read
PostgreSQL

Data Modeling & Schema Design

Design tables, keys, and constraints that keep data correct

Relational Modeling

Start by identifying entities (Users, Orders, Products) and the relationships between them. Normalize to reduce duplication and improve consistency.

Keys & Constraints

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  name TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id),
  title TEXT NOT NULL,
  body TEXT,
  published BOOLEAN DEFAULT false,
  created_at TIMESTAMP DEFAULT NOW()
);

Best Practices

  • • Use PRIMARY KEY for stable identifiers
  • • Add UNIQUE constraints for emails, slugs, etc.
  • • Use NOT NULL for required fields
  • • Prefer timestamp columns for auditing

Continue Learning