Blog
    11 min read

    Database Design Patterns That Prevent Rewrites

    Database Design Patterns That Prevent Rewrites

    Technical Note: This article contains extensive PostgreSQL schema examples, including UUIDs, soft deletes, JSONB columns, and temporal tables. The patterns are framework-agnostic.


    The Schema That Haunts You

    I've seen companies spend six months migrating away from a database schema that took two days to design. The original developer made reasonable decisions with the information they had. But those decisions compounded over three years into a structure that couldn't support the business.

    Database schemas are the foundation of your application. Get them wrong, and you're building on quicksand.

    Here are the patterns we use to design schemas that age gracefully.

    Pattern 1: UUIDs Over Auto-Increment

    Auto-incrementing IDs seem simpler. They're not.

    -- ❌ Auto-increment: Creates problems at scale
    CREATE TABLE orders (
      id SERIAL PRIMARY KEY,
      user_id INTEGER REFERENCES users(id)
    );
    
    -- ✅ UUID: Works everywhere
    CREATE TABLE orders (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      user_id UUID REFERENCES users(id)
    );
    

    Why UUIDs win:

    1. Merge databases without conflicts. Combining two SERIAL tables requires remapping every ID.
    2. Generate IDs client-side. Create records optimistically before the server responds.
    3. No information leakage. Sequential IDs reveal how many records exist.
    4. Distributed systems ready. No central authority needed to assign IDs.

    The performance difference is negligible with proper indexing.

    Pattern 2: Soft Deletes With Timestamps

    Never truly delete data. You'll need it for audits, debugging, or that user who wants to restore their account.

    CREATE TABLE projects (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      name TEXT NOT NULL,
      created_at TIMESTAMPTZ DEFAULT now(),
      updated_at TIMESTAMPTZ DEFAULT now(),
      deleted_at TIMESTAMPTZ  -- NULL means not deleted
    );
    
    -- Automatically filter deleted records
    CREATE VIEW active_projects AS
    SELECT * FROM projects WHERE deleted_at IS NULL;
    

    This pattern:

    • Preserves data integrity for foreign keys
    • Enables "undo" functionality
    • Provides audit trail for compliance
    • Makes debugging production issues possible

    Pattern 3: JSON Columns for Flexible Data

    Not everything fits in rigid columns. JSON columns give you flexibility without sacrificing queryability:

    CREATE TABLE events (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      event_type TEXT NOT NULL,
      payload JSONB NOT NULL,
      created_at TIMESTAMPTZ DEFAULT now()
    );
    
    -- Index specific JSON paths for performance
    CREATE INDEX idx_events_user_id ON events ((payload->>'user_id'));
    
    -- Query JSON data efficiently
    SELECT * FROM events 
    WHERE payload->>'action' = 'purchase'
    AND (payload->>'amount')::numeric > 100;
    

    Use JSON for:

    • Event data with varying structures
    • User preferences and settings
    • Third-party API responses
    • Feature flags and configuration

    Don't use JSON for:

    • Data you query frequently with complex conditions
    • Relationships between entities
    • Anything requiring strong type safety

    Pattern 4: Temporal Tables for History

    When you need to know what data looked like at any point in time:

    -- Main table
    CREATE TABLE products (
      id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
      name TEXT NOT NULL,
      price DECIMAL(10,2) NOT NULL,
      updated_at TIMESTAMPTZ DEFAULT now()
    );
    
    -- History table
    CREATE TABLE products_history (
      id UUID,
      name TEXT,
      price DECIMAL(10,2),
      valid_from TIMESTAMPTZ,
      valid_to TIMESTAMPTZ,
      PRIMARY KEY (id, valid_from)
    );
    
    -- Trigger to maintain history
    CREATE OR REPLACE FUNCTION track_product_history()
    RETURNS TRIGGER AS $$
    BEGIN
      IF TG_OP = 'UPDATE' THEN
        INSERT INTO products_history (id, name, price, valid_from, valid_to)
        VALUES (OLD.id, OLD.name, OLD.price, OLD.updated_at, NEW.updated_at);
      END IF;
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
    

    This enables:

    • "What was the price on January 15th?"
    • Audit compliance requirements
    • Debugging data corruption issues
    • Time-travel queries for analytics

    Pattern 5: Enum Tables Over Check Constraints

    Check constraints seem cleaner. Enum tables are more maintainable:

    -- ❌ Check constraint: Requires migration to add values
    CREATE TABLE orders (
      status TEXT CHECK (status IN ('pending', 'processing', 'shipped', 'delivered'))
    );
    
    -- ✅ Enum table: Add values with simple INSERT
    CREATE TABLE order_statuses (
      id TEXT PRIMARY KEY,
      display_name TEXT NOT NULL,
      sort_order INTEGER
    );
    
    INSERT INTO order_statuses VALUES 
      ('pending', 'Pending', 1),
      ('processing', 'Processing', 2),
      ('shipped', 'Shipped', 3),
      ('delivered', 'Delivered', 4);
    
    CREATE TABLE orders (
      status TEXT REFERENCES order_statuses(id)
    );
    

    Benefits:

    • Add new statuses without migrations
    • Store metadata (display names, colors, sort order)
    • Foreign key ensures data integrity
    • Self-documenting: query the table to see all valid values

    The Migration Safety Net

    Even with good patterns, schemas evolve. Make migrations safe:

    1. Always backwards compatible. New columns should be nullable or have defaults.
    2. Separate deploy from migrate. Deploy code that handles both old and new schema, then migrate.
    3. Test migrations on production data copies. That 5-second migration might take 5 hours on real data.

    Good database design isn't about predicting the future. It's about creating structures flexible enough to evolve when the future arrives.