Schema Design Patterns & Case Studies
Identifier strategies (auto-increment, UUIDv4/v7, ULID, Snowflake), money and time types, soft deletes, audit/history tables, multi-tenancy models, polymorphic associations, EAV vs JSONB, trees in SQL, zero-downtime migrations, and full schemas for e-commerce, social feed and booking systems.
Identifiers
| Strategy | Size | Ordered | Generated where | Notes |
|---|---|---|---|---|
BIGINT identity / sequence | 8 B | ✓ | database | simplest; enumerable; hard across shards |
| UUIDv4 | 16 B | ✗ | anywhere | random; index fragmentation |
| UUIDv7 (RFC 9562) | 16 B | ✓ (ms) | anywhere | time-ordered UUID; good default for distributed IDs |
| ULID | 16 B (26-char string) | ✓ (ms) | anywhere | lexicographically sortable, Crockford base32 |
| Snowflake | 8 B | ✓ | ID service / each node | 41-bit ms time + 10-bit machine + 12-bit sequence |
| Natural key | varies | — | business | can change (emails do!) |
See the unique ID generator case study for the Snowflake design.
Data types that bite
- Money → integer minor units or
NUMERIC+ currency code. NeverFLOAT. - Time →
TIMESTAMPTZin UTC; store the IANA zone separately when local time matters. - Strings →
TEXTwithCHECK (char_length(x) <= n)(Postgres) or sizedVARCHAR; case-insensitive uniqueness vialower()index orcitext. - Enums → lookup table or
CHECK (status IN (...)); native enums are hard to change in some databases. - Booleans that are really states → a status column (
pending/active/suspended) ages better thanis_active+is_suspended. - JSON →
JSONBfor genuinely variable attributes; promote frequently queried fields to real columns.
Soft deletes
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;
CREATE UNIQUE INDEX users_email_active ON users (lower(email)) WHERE deleted_at IS NULL;
CREATE VIEW active_users AS SELECT * FROM users WHERE deleted_at IS NULL;
Audit and history
| Pattern | How | Use |
|---|---|---|
| Created/updated columns | created_at, updated_at, updated_by | basic provenance |
| History table | trigger copies the old row into users_history with valid_from/valid_to | "what did this look like on date X?" |
| Temporal tables | SQL:2011 system-versioned tables (SQL Server, MariaDB) | built-in history |
| Audit log | append-only audit_event(actor, action, entity, before, after, at) | compliance, security |
| Event sourcing | events are the source of truth; state is a projection | full history + replay (see Queues & streams) |
Multi-tenancy
-- Postgres Row-Level Security for the shared-schema model
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- per request/transaction:
SET LOCAL app.tenant_id = '42';
Polymorphic associations
"A comment can belong to a post, a photo or a video."
| Approach | Schema | Trade-off |
|---|---|---|
| Polymorphic columns | commentable_type, commentable_id | no FK integrity (Rails default) |
| Exclusive FKs | post_id, photo_id, video_id + CHECK exactly one non-null | real FKs, sparse columns |
| Shared parent | content(id) supertype; post/photo/video share its id; comments → content | clean integrity, extra table |
| Separate tables | post_comment, photo_comment | simple, duplicated logic |
EAV vs JSONB
Entity–Attribute–Value (entity_id, attribute, value) handles arbitrary attributes but makes every query a self-join pivot and loses typing. Prefer JSONB with GIN indexes for variable attributes (product specifications), promoting hot attributes to columns.
Trees and graphs in SQL
| Model | Subtree query | Move subtree | Notes |
|---|---|---|---|
Adjacency list (parent_id) | recursive CTE | update one row | default choice |
Materialised path (ltree) | prefix match | rewrite descendants | great for categories |
| Nested sets | range query | renumber many rows | read-mostly |
| Closure table | join on ancestor | insert/delete many rows | fastest queries, multiple parents |
Zero-downtime migrations (expand → migrate → contract)
Case study 1: e-commerce core
CREATE TABLE product (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
attributes JSONB NOT NULL DEFAULT '{}', -- variable specs
price_cents BIGINT NOT NULL CHECK (price_cents >= 0),
currency CHAR(3) NOT NULL DEFAULT 'INR'
);
CREATE TABLE inventory (
product_id BIGINT PRIMARY KEY REFERENCES product(id),
on_hand INT NOT NULL CHECK (on_hand >= 0),
reserved INT NOT NULL DEFAULT 0 CHECK (reserved >= 0 AND reserved <= on_hand)
);
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id BIGINT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('pending','paid','shipped','delivered','cancelled','refunded')),
total_cents BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
shipping_address JSONB NOT NULL, -- snapshot at order time
idempotency_key TEXT UNIQUE, -- safe retries of "place order"
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_created ON orders (customer_id, created_at DESC);
CREATE TABLE order_item (
order_id BIGINT REFERENCES orders(id) ON DELETE CASCADE,
line_no INT,
product_id BIGINT NOT NULL REFERENCES product(id),
qty INT NOT NULL CHECK (qty > 0),
unit_price_cents BIGINT NOT NULL, -- price at purchase time
PRIMARY KEY (order_id, line_no)
);
-- reserve stock atomically (no oversell, no lost update)
UPDATE inventory SET reserved = reserved + $qty
WHERE product_id = $pid AND on_hand - reserved >= $qty; -- 0 rows → out of stock
Case study 2: social feed
CREATE TABLE app_user (id BIGINT PRIMARY KEY, handle TEXT UNIQUE NOT NULL, follower_count INT NOT NULL DEFAULT 0);
CREATE TABLE follow (
follower_id BIGINT, followee_id BIGINT, created_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follow_followee ON follow (followee_id, follower_id); -- "who follows X"
CREATE TABLE post (
id BIGINT PRIMARY KEY, -- Snowflake: time-ordered
author_id BIGINT NOT NULL, body TEXT, created_at TIMESTAMPTZ NOT NULL,
like_count INT NOT NULL DEFAULT 0 -- denormalised counter
);
CREATE INDEX post_author_id ON post (author_id, id DESC);
CREATE TABLE post_like (user_id BIGINT, post_id BIGINT, PRIMARY KEY (post_id, user_id));
-- the home timeline itself is usually precomputed in a cache (fan-out on write);
-- see the News Feed case study
Case study 3: seat booking (no double booking)
CREATE TABLE seat_hold (
show_id BIGINT, seat_id TEXT,
user_id BIGINT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('held','booked')),
expires_at TIMESTAMPTZ,
PRIMARY KEY (show_id, seat_id) -- at most one hold/booking per seat
);
-- try to hold a seat: the PK makes concurrent holds fail cleanly
INSERT INTO seat_hold (show_id, seat_id, user_id, status, expires_at)
VALUES (77, 'C12', 42, 'held', now() + interval '10 minutes')
ON CONFLICT (show_id, seat_id) DO UPDATE
SET user_id = EXCLUDED.user_id, expires_at = EXCLUDED.expires_at
WHERE seat_hold.status = 'held' AND seat_hold.expires_at < now(); -- steal only expired holds
-- affected rows = 0 → seat taken
-- Postgres exclusion constraint for time ranges (meeting rooms, rentals)
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_booking (
room_id BIGINT, during TSTZRANGE,
EXCLUDE USING gist (room_id WITH =, during WITH &&) -- no overlapping bookings per room
);
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.