{}DSA Atlas

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.

Intermediate → Advanced6 interview questions

Identifiers

StrategySizeOrderedGenerated whereNotes
BIGINT identity / sequence8 B✓databasesimplest; enumerable; hard across shards
UUIDv416 B✗anywhererandom; index fragmentation
UUIDv7 (RFC 9562)16 B✓ (ms)anywheretime-ordered UUID; good default for distributed IDs
ULID16 B (26-char string)✓ (ms)anywherelexicographically sortable, Crockford base32
Snowflake8 B✓ID service / each node41-bit ms time + 10-bit machine + 12-bit sequence
Natural keyvaries—businesscan 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. Never FLOAT.
  • Time → TIMESTAMPTZ in UTC; store the IANA zone separately when local time matters.
  • Strings → TEXT with CHECK (char_length(x) <= n) (Postgres) or sized VARCHAR; case-insensitive uniqueness via lower() index or citext.
  • 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 than is_active + is_suspended.
  • JSON → JSONB for genuinely variable attributes; promote frequently queried fields to real columns.

Soft deletes

SQL
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

PatternHowUse
Created/updated columnscreated_at, updated_at, updated_bybasic provenance
History tabletrigger copies the old row into users_history with valid_from/valid_to"what did this look like on date X?"
Temporal tablesSQL:2011 system-versioned tables (SQL Server, MariaDB)built-in history
Audit logappend-only audit_event(actor, action, entity, before, after, at)compliance, security
Event sourcingevents are the source of truth; state is a projectionfull history + replay (see Queues & streams)

Multi-tenancy

Shared schema orders (tenant_id, …) users (tenant_id, …) cheap · RLS for isolation Schema per tenant acme.* globex.* middle ground DB per tenant db_acme db_globex strongest isolation · costly
Isolation and cost increase from left to right.
SQL
-- 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."

ApproachSchemaTrade-off
Polymorphic columnscommentable_type, commentable_idno FK integrity (Rails default)
Exclusive FKspost_id, photo_id, video_id + CHECK exactly one non-nullreal FKs, sparse columns
Shared parentcontent(id) supertype; post/photo/video share its id; comments → contentclean integrity, extra table
Separate tablespost_comment, photo_commentsimple, 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

ModelSubtree queryMove subtreeNotes
Adjacency list (parent_id)recursive CTEupdate one rowdefault choice
Materialised path (ltree)prefix matchrewrite descendantsgreat for categories
Nested setsrange queryrenumber many rowsread-mostly
Closure tablejoin on ancestorinsert/delete many rowsfastest queries, multiple parents

Zero-downtime migrations (expand → migrate → contract)

1. Expandadd nullable column 2. Dual writeold + new 3. Backfillbatches, throttled 4. Switch readsverify, monitor 5. Contractdrop old (later) every step is deployable and reversible; old and new code versions both work at each step
Rename a column, split a table or change a type without downtime.

Case study 1: e-commerce core

SQL
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

SQL
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)

SQL
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

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.