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.
The choices that matter
| For | Use | Never use | Why |
|---|---|---|---|
| Money | numeric(12,2) | float, real | Binary floats cannot represent 0.10 — totals drift |
| Timestamps | timestamptz | timestamp | Without a zone you are storing an ambiguous instant |
| Text | text | varchar(255) by habit | Identical performance; 255 is a MySQL artefact |
| Email / usernames | citext | text + lower() everywhere | Case-insensitive comparison and uniqueness for free |
| Surrogate keys | bigint GENERATED ALWAYS AS IDENTITY | serial | Standard SQL; serial has ownership quirks |
| Public identifiers | uuid or a prefixed text id | Sequential integers | Sequential ids leak volume and enable enumeration |
| Fixed sets | enum or text + CHECK | smallint codes | Readable in the database, enforced by the database |
| Booleans | boolean | char(1) 'Y'/'N' | Three-valued logic you did not ask for |
| Flexible attributes | jsonb | text holding JSON | Indexable, queryable, validated as JSON |
| IP addresses | inet | text | Subnet operators and correct ordering |
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
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)
);
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
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
-- 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'));
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
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
| Operation | Locks the table? | Safe approach |
|---|---|---|
| Add a nullable column | Brief | Safe |
| Add a column with a default | Brief since PG 11 | Safe on modern versions |
Add NOT NULL | Full scan | Add a CHECK … NOT VALID, VALIDATE, then set NOT NULL |
| Create an index | Blocks writes | CREATE INDEX CONCURRENTLY |
| Change a column type | Full rewrite | New column, backfill in batches, swap, drop |
| Add a foreign key | Scans both tables | NOT VALID, then VALIDATE CONSTRAINT |
| Drop a column | Brief | Safe — but only after no deployed code reads it |
-- 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;
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.