Chapter 02

Schema design and data types

The type system is your cheapest bug-prevention tool. A column that cannot hold a wrong value is worth more than the validation code you would otherwise write three times.

⏱ 16 min readLevel: beginner → intermediate

The choices that matter

ForUseNever useWhy
Moneynumeric(12,2)float, realBinary floats cannot represent 0.10 — totals drift
TimestampstimestamptztimestampWithout a zone you are storing an ambiguous instant
Texttextvarchar(255) by habitIdentical performance; 255 is a MySQL artefact
Email / usernamescitexttext + lower() everywhereCase-insensitive comparison and uniqueness for free
Surrogate keysbigint GENERATED ALWAYS AS IDENTITYserialStandard SQL; serial has ownership quirks
Public identifiersuuid or a prefixed text idSequential integersSequential ids leak volume and enable enumeration
Fixed setsenum or text + CHECKsmallint codesReadable in the database, enforced by the database
Booleansbooleanchar(1) 'Y'/'N'Three-valued logic you did not ask for
Flexible attributesjsonbtext holding JSONIndexable, queryable, validated as JSON
IP addressesinettextSubnet operators and correct ordering
timestamp vs timestamptz

timestamptz does not store a time zone. It stores an absolute instant (UTC) and converts on input and output using the session's zone. That is what you want. Plain timestamp stores wall-clock text with no instant — so two rows written a second apart in different regions can compare in the wrong order.

Constraints are executable documentation

V1__init.sql
CREATE TYPE order_status AS ENUM
    ('DRAFT','PLACED','PAID','FULFILLED','DELIVERED','CANCELLED','REFUNDED');

CREATE TABLE customer_order (
    order_id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id  bigint        NOT NULL
                 REFERENCES customer (customer_id) ON DELETE RESTRICT,
    reference    text          NOT NULL UNIQUE,
    status       order_status  NOT NULL DEFAULT 'DRAFT',
    total_amount numeric(12,2) NOT NULL DEFAULT 0 CHECK (total_amount >= 0),
    currency     char(3)       NOT NULL DEFAULT 'EUR'
                 CHECK (currency ~ '^[A-Z]{3}$'),
    metadata     jsonb         NOT NULL DEFAULT '{}',
    version      integer       NOT NULL DEFAULT 0,
    placed_at    timestamptz,
    created_at   timestamptz   NOT NULL DEFAULT now(),

    -- a placed order must have a placement time, and vice versa
    CONSTRAINT placed_at_consistent CHECK (
      (status = 'DRAFT'  AND placed_at IS NULL) OR
      (status <> 'DRAFT' AND placed_at IS NOT NULL)
    )
);

CREATE TABLE order_line (
    line_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id   bigint        NOT NULL
               REFERENCES customer_order ON DELETE CASCADE,
    product_id bigint        NOT NULL REFERENCES product,
    quantity   integer       NOT NULL CHECK (quantity > 0),
    unit_price numeric(12,2) NOT NULL CHECK (unit_price >= 0),

    -- the same product must not appear twice on one order
    UNIQUE (order_id, product_id)
);
ON DELETE: choose deliberately

RESTRICT on customer_id means you cannot delete a customer who has orders — correct, because you would be destroying financial history. CASCADE on order_line means deleting an order removes its lines — also correct, because a line has no meaning alone. The default is NO ACTION; picking explicitly is part of the design.

Generated and identity columns

computed by the database, always correct
ALTER TABLE order_line
  ADD COLUMN line_total numeric(12,2)
  GENERATED ALWAYS AS (quantity * unit_price) STORED;

-- full-text search vector, maintained automatically
ALTER TABLE product
  ADD COLUMN search_vector tsvector
  GENERATED ALWAYS AS (
    to_tsvector('english', coalesce(name,'') || ' ' || coalesce(description,''))
  ) STORED;

CREATE INDEX idx_product_search ON product USING gin (search_vector);

A generated column cannot drift from its inputs, which is exactly the failure mode of the same value maintained by application code in four places.

JSONB in practice

flexible, but not unconstrained
-- containment: does metadata include these key/value pairs?
SELECT * FROM customer_order
WHERE metadata @> '{"channel":"mobile"}';

-- key existence
SELECT * FROM customer_order WHERE metadata ? 'campaign';

-- extract as text (->>) or as jsonb (->)
SELECT reference,
       metadata ->> 'campaign'          AS campaign,
       (metadata -> 'flags' ->> 'gift')::boolean AS is_gift
FROM   customer_order;

-- update a single key without rewriting the document
UPDATE customer_order
SET    metadata = jsonb_set(metadata, '{channel}', '"phone"')
WHERE  order_id = 42;

-- expand an array of objects into rows
SELECT o.reference, item ->> 'sku' AS sku
FROM   customer_order o,
       jsonb_array_elements(o.metadata -> 'giftItems') AS item;

-- still constrain it
ALTER TABLE customer_order ADD CONSTRAINT metadata_channel_valid
  CHECK (metadata ->> 'channel' IN ('web','mobile','phone','partner'));
Use JSONB for the edges, not the core

Anything you filter, join, aggregate or report on belongs in a real column with a real type. JSONB is for genuinely variable attributes — per-tenant settings, third-party payloads, feature metadata. A schema where status lives inside a JSONB document is a schema you will regret.

Arrays and ranges

two under-used types
ALTER TABLE product ADD COLUMN tags text[] NOT NULL DEFAULT '{}';
CREATE INDEX idx_product_tags ON product USING gin (tags);

SELECT * FROM product WHERE tags @> ARRAY['sale'];       -- contains
SELECT * FROM product WHERE tags && ARRAY['sale','new']; -- overlaps

-- ranges make "no double booking" a database guarantee
CREATE TABLE reservation (
    reservation_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    resource_id    bigint NOT NULL,
    during         tstzrange NOT NULL,

    EXCLUDE USING gist (resource_id WITH =, during WITH &&)
);
-- an overlapping insert now fails, atomically, with no application locking

Migrations that do not cause an outage

OperationLocks the table?Safe approach
Add a nullable columnBriefSafe
Add a column with a defaultBrief since PG 11Safe on modern versions
Add NOT NULLFull scanAdd a CHECK … NOT VALID, VALIDATE, then set NOT NULL
Create an indexBlocks writesCREATE INDEX CONCURRENTLY
Change a column typeFull rewriteNew column, backfill in batches, swap, drop
Add a foreign keyScans both tablesNOT VALID, then VALIDATE CONSTRAINT
Drop a columnBriefSafe — but only after no deployed code reads it
the two-step pattern
-- step 1: instant, no scan
ALTER TABLE customer_order
  ADD CONSTRAINT total_non_negative CHECK (total_amount >= 0) NOT VALID;

-- step 2: scans without blocking writes
ALTER TABLE customer_order VALIDATE CONSTRAINT total_non_negative;
Always set a lock timeout in migrations

A migration waiting for a lock queues every query behind it, and a five-second schema change becomes a five-minute outage. Begin every migration with SET lock_timeout = '3s'; so it fails fast instead of taking the site down.

Why store money as numeric rather than double precision?

0.1 + 0.2 is not 0.3 in binary floating point. Over thousands of order lines that error accumulates into a real reconciliation problem. numeric is slower and larger — and correct, which is the only property that matters for money.