Interview Q&A · SQL · 12 questions in this topic
Schema Design & Security — SQL Interview Q&A
Senior-level design — normalization trade-offs, key strategies, migrations and SQL injection defense. Part of Design & Security · 192 questions in the SQL bank.
How do you design a schema from scratch (orders example)?
Answer
Identify entities (customers, orders, lines, products), give each a surrogate key, relate via foreign keys, normalize to 3NF, add constraints (NOT NULL, CHECK, UNIQUE), index access paths, and seed with representative data for EXPLAIN testing.
Entities, keys, relations, constraints, indexes — the design march in order.
Key points
- 1Entities + surrogate keys.
- 2Relations via foreign keys.
- 3Constraints, then indexes.
Example
CREATE TABLE orders ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers (id), created_at TIMESTAMPTZ NOT NULL DEFAULT now() );
💡 Walk entities-to-indexes in order — interviewers grade the sequence.
When do you denormalize, and what does it cost?
Answer
Denormalize for proven read hotspots: counters, rollup columns, star-schema dimensions —Trading write complexity (sync logic, triggers, jobs) for read speed. Costs: storage duplication, update anomalies, sync bugs. Mitigate with single-writer paths, reconciliation jobs, and comments documenting the redundancy contract.
Measure first, duplicate deliberately, reconcile always.
Key points
- 1Why — proven read hotspots only.
- 2Cost — sync logic and anomaly risk.
- 3Guard — single writer plus reconciliation.
Surrogate vs natural vs UUID keys — how do you choose?
Answer
Surrogate integers (IDENTITY/SERIAL): compact, fast, meaningless — the default. Natural keys: meaningful but mutable (emails change). UUIDs: globally unique, merge-safe, larger and random-IO heavy (v7/ordered variants mitigate).
Default integer surrogate; UUIDs for distributed/merge-heavy systems; natural keys behind UNIQUE, never as PK.
Key points
- 1Integer surrogate — compact default.
- 2UUID — distributed merge-safety, larger.
- 3Natural — UNIQUE constraint, not PK.
Example
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- distributed-safe -- vs: id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY
💡 Meaningless-and-stable wins PK; meaningful gets UNIQUE.
How do you model hierarchies and trees (adjacency, path, nested sets)?
Answer
Adjacency list (parent_id): simple writes, recursive-CTE reads. Path enumeration (ltree/materialized path): fast subtree queries, painful moves. Nested sets (lft/rgt): fast subtree reads, expensive writes. Closure tables: explicit ancestor pairs, balanced both.
Adjacency default; nested sets for read-heavy static trees; closure for flexible graphs.
Key points
- 1Adjacency — simple, recursive reads.
- 2Path — fast subtrees, hard moves.
- 3Nested sets — fast reads, costly writes.
Example
-- adjacency + recursive CTE (default shape): -- id, parent_id ... WITH RECURSIVE sub AS (...)
💡 Read-vs-write profile picks the model — state the trade.
How do you model many-to-many relationships?
Answer
Junction table with composite key of both foreign keys (plus relationship attributes like enrolled_at), CASCADE or RESTRICT per ownership, composite indexes both directions. The junction is a first-class entity when it gains attributes.
Two FKs plus composite PK is the whole pattern.
Example
CREATE TABLE enrollments ( student_id BIGINT REFERENCES students (id) ON DELETE CASCADE, course_id BIGINT REFERENCES courses (id) ON DELETE CASCADE, enrolled_at DATE NOT NULL DEFAULT CURRENT_DATE, PRIMARY KEY (student_id, course_id) );
How do SQL injection attacks work and how do you stop them?
Answer
Untrusted input concatenated into SQL alters query structure (' OR '1'='1, stacked queries, UNION exfiltration). Defense: parameterized queries/prepared statements (values never parse as code), least-privilege DB roles, input validation as depth — never string building.
ORMs still inject through raw fragments — parameterization is the rule at every layer.
Key points
- 1Attack — input becomes code via concatenation.
- 2Defense — parameters, never interpolation.
- 3Depth — least privilege, validation.
Example
-- SAFE (parameter, never formatted in): -- cur.execute("SELECT * FROM users WHERE name = %s", (name,))
How do you manage schema migrations safely?
Answer
Versioned migration files (up/down), expand-then-contract for compatibility (add nullable → backfill → constrain → drop old), backward-compatible steps for zero-downtime deploys, tested rollbacks, and CI running migrations on copies.
App and schema deploy in lockstep-safe order: expand first, contract after clients move.
Key points
- 1Versioned — every change a file.
- 2Compatible — expand before contract.
- 3Reversible — tested rollback path.
💡 Expand-contract is the zero-downtime mantra.
How do you store passwords, tokens and secrets?
Answer
Passwords: argon2/bcrypt/scrypt hashes with per-password salts — never plaintext, never reversible encryption, never MD5/SHA-fast-hashes. Tokens: random bytes hashed at rest (compare hashes). Secrets: vault/KMS, never in code or dumps.
Breach-model thinking: the database will leak someday — hashes must survive it.
Key points
- 1Passwords — slow salted hashes (argon2/bcrypt).
- 2Tokens — random, hashed at rest.
- 3Secrets — vaults, never code.
Example
-- users(password_hash TEXT NOT NULL) -- argon2 string, never plaintext
How do you implement row-level access control?
Answer
PostgreSQL Row-Level Security policies (USING for reads, WITH CHECK for writes) enforced per role — the database, not the app, guarantees isolation. Views with security_barrier plus roles work elsewhere. Tenant-id columns plus policies give multi-tenant isolation.
Enforcement in the database survives every buggy query and leaked connection.
Example
-- PostgreSQL RLS: -- CREATE POLICY tenant_iso ON orders USING (tenant_id = current_setting('app.tenant')::int);
💡 Database-enforced beats app-filtered is the security argument.
How do you audit changes (history tables, triggers)?
Answer
History tables (row versions with valid-from/to timestamps) fed by triggers or application writes — who changed what, when. Temporal/system-versioned tables automate this where supported. Audit writes must be append-only (revoke UPDATE/DELETE) to stay trustworthy.
Append-only history is the compliance backbone.
Example
-- trigger-maintained history: -- CREATE TRIGGER audit AFTER UPDATE OR DELETE ON orders ...
How do you handle time-travel queries (as-of snapshots)?
Answer
System-versioned temporal tables (FOR SYSTEM_TIME AS OF) answer as-of directly where supported. Manual validity ranges (valid_from/valid_to with half-open containment queries) work everywhere. Event sourcing rebuilds state by replaying — full history at replay cost.
Half-open containment (from <= t AND t < to) is the portable core pattern.
Example
-- portable validity query: SELECT * FROM prices WHERE product_id = 7 AND valid_from <= '2024-06-01' AND '2024-06-01' < valid_to;
How do you back up and restore (pg_dump, PITR)?
Answer
Logical dumps (pg_dump) for portability and small DBs; physical base backups plus WAL archiving for point-in-time recovery on large systems. Restore drills (not backup logs) prove recoverability — untested backups are Schrödinger backups.
RPO/RTO targets pick the strategy: dumps for simplicity, PITR for tight windows.
Key points
- 1Dumps — portable, small-scale.
- 2PITR — base + WAL, any moment.
- 3Drills — restores tested, not assumed.
💡 Untested backups are not backups is the line to close on.
Recommended resourcesAffiliate links · may earn us a commission