What is a DBMS?
Software that manages data storage, querying, concurrency, recovery and security. It abstracts physical storage and enforces integrity constraints.
app → SQL → DBMS → files/pages
Databases · 10 sections
ACID, indexing, replication and SQL-vs-NoSQL — the database questions backend rounds keep returning to.
Software that manages data storage, querying, concurrency, recovery and security. It abstracts physical storage and enforces integrity constraints.
app → SQL → DBMS → files/pages
Atomicity (all-or-nothing), Consistency (invariants hold), Isolation (concurrent txns don't interfere), Durability (committed survives crash).
A rollback on failure
C constraints preserved
I serializable/snapshot
D WAL + fsync
A transaction either fully applies or fully rolls back. Implemented via undo logs / rollback segments; partial failure triggers rollback.
BEGIN; ...; COMMIT; -- all or nothing
ROLLBACK on error
A transaction moves the DB from one valid state to another, preserving constraints (PK, FK, CHECK, triggers).
FK violations abort txn
CHECK constraints enforced
Concurrent transactions behave as if serial. Real systems trade strictness for throughput via isolation levels.
SERIALIZABLE > REPEATABLE READ > READ COMMITTED > READ UNCOMMITTED
Once committed, data survives crashes/power loss via WAL flushed to disk (fsync) plus checkpoints.
commit → fsync(WAL) → durable
checkpoint → flush data pages later
Each column holds atomic (indivisible) values; no repeating groups; each row unique. Eliminates multi-valued attributes.
phone1,phone2 → phones table (1NF)
1NF plus no partial dependency: every non-key attribute depends on the entire composite primary key.
order_items(order_id,product_id,product_name) → product_name depends on product_id only (violation)
2NF plus no transitive dependency: non-key attributes depend only on the key, not on other non-key attributes.
emp(dept,dept_head) → dept_head depends on dept (violation)
Every determinant is a candidate key. Stricter than 3NF; handles anomalies when a non-superkey determines attributes.
if X→Y then X must be a superkey
Intentionally adding redundancy to speed reads (precomputed joins/aggregates). Trade write cost and consistency for read performance.
store order_total on orders to avoid SUM(items)
Entities (tables), attributes (columns), relationships (1:1, 1:N, M:N). M:N resolved via junction table.
students ⋈ enrollments ⋈ courses
Primary key uniquely identifies a row (not null, unique). Foreign key references PK of another table, enforcing referential integrity.
orders.customer_id → customers.id
NULL means unknown. Comparisons yield UNKNOWN (not false), so no rows match; use IS NULL / IS NOT NULL. Aggregates ignore NULL except COUNT(*) counts rows.
WHERE x = NULL -- UNKNOWN (no rows match)
WHERE x IS NULL
COUNT(col) ignores NULLs; COUNT(*) counts rows
Super key uniquely identifies rows (may have extra attrs). Candidate key is minimal super key. One chosen as primary key.
OLTP: many short transactions, row-oriented, strong consistency. OLAP: large scans/aggregations, columnar, batch. Choose schema/storage accordingly.
OLTP: normalized, B+ tree
OLAP: denormalized, columnar
Auxiliary data structure (usually B+ tree) mapping key values to row locations, speeding lookups at cost of write/space. Balanced tree of pages; O(log n) point lookups and efficient range scans. Default index type in most RDBMS.
CREATE INDEX idx ON t(col);
leaf pages linked → range scan sorted
B+ tree stores all data in leaves linked in order; internal nodes only keys. Better range scans and higher fanout. Most DBs use B+.
B+ leaves → doubly linked list
Hashes key to bucket; O(1) equality lookups but no range/order support. Used for exact-match and memory stores.
WHERE id = 5 -- hash-friendly
WHERE id > 5 -- not
Index on multiple columns. Column order matters: leftmost prefix rule. Equality columns first, then sort, then range (ESR).
INDEX(a,b,c): usable for a; a,b; a,b,c
not for b alone
Index contains all columns needed by query, so engine answers from index without table lookup (index-only scan).
SELECT a,b FROM t WHERE a=1 -- index(a,b) covers
Clustered index determines physical row order (one per table, often PK). Non-clustered is separate structure pointing to rows/heap.
InnoDB: PK is clustered
secondary index → PK lookup
Usually clustered B+ tree on PK. In InnoDB table is organized by PK (clustered).
Slows writes (maintain tree), costs disk/RAM, and low-cardinality/non-sargable predicates may be ignored by planner.
write cost ↑ · space ↑
WHERE YEAR(date)=2026 hides index
Predicate can use index when column is bare (no function/expression). Wrap values, not columns.
WHERE date >= '2026-01-01' -- sargable
WHERE YEAR(date)=2026 -- not
Column selectivity = distinct/total (cardinality ratio). Query selectivity = matched/total (predicate). High-selectivity columns/indexes help; low-cardinality (boolean) rarely worth a standalone index.
column: COUNT(DISTINCT col)/COUNT(*)
query: rows_matched/rows_total
Index only subset of rows matching a predicate; smaller and faster for common filtered queries.
CREATE INDEX ON orders(status) WHERE status='pending';
Active → partially committed → committed; or failed → aborted → rolled back. Savepoints allow partial rollback.
BEGIN; ...; COMMIT/ROLLBACK;
ANSI levels by anomaly: Read Uncommitted (dirty reads allowed), Read Committed (no dirty), Repeatable Read (no non-repeatable), Serializable (no phantoms). Engines differ: Postgres RR is snapshot isolation (no phantoms, but write skew possible); MySQL/InnoDB RR uses next-key/gap locks. Serializable: Postgres SSI; InnoDB locking reads.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- Postgres RR = snapshot isolation; MySQL RR = gap locks
Reading uncommitted data from another txn that may rollback. Prevented by Read Committed and above.
Re-reading same row returns different value because another txn committed an update between reads. Prevented by Repeatable Read+.
Re-running a range query returns new rows inserted by another committed txn. Prevented by Serializable (or gap locks).
Two txns read same value, both write; one overwrites the other. Prevented by locking or optimistic versioning.
Two txns read overlapping data and write disjoint subsets, violating constraint. Serializable or predicate locks needed.
Multi-Version Concurrency Control: readers see snapshot, writers create new versions; no read locks. Used by Postgres/InnoDB.
snapshot isolation: readers don't block writers
Shared (S) for reads, Exclusive (X) for writes. Intent locks (IS/IX) at table level. Lock compatibility matrix governs waiting.
S compatible with S; X with none
Two txns each hold lock the other wants. DB detects and aborts one (victim) with deadlock error; app retries.
retry on SQLSTATE 40001 / deadlock
Named points inside a txn to rollback partially without aborting whole txn. Useful in nested operations.
SAVEPOINT sp1; ...; ROLLBACK TO sp1;
Distributed txn protocol: prepare (vote) then commit. Ensures atomicity across nodes but blocking on coordinator failure.
prepare → vote → commit/abort
Postgres implements Serializable via Serializable Snapshot Isolation (SSI), tracking read-write dependencies and aborting conflicting txns (SQLSTATE 40001) instead of locking.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- retry on 40001
Leader handles writes and replicates to followers for reads. Async = fast but possible data loss on failover; sync = safe but slower.
write → leader → (async|sync) → followers
Commit waits for a named standby to acknowledge. Stronger durability/consistency, higher write latency. Configure both settings; without standby names commits are not synchronous to replicas.
synchronous_commit = on
synchronous_standby_names = 'FIRST 1 (replica1)'
Leader commits without waiting; followers catch up. Fast writes but lag and possible loss on failover.
replication lag → stale reads
Wait for at least one replica to receive (ack) the transaction, not to apply it. Balance of safety and latency (MySQL semi-sync).
rpl_semi_sync_source_timeout -- ack on receive, not apply
On primary failure, promote a replica. Automatic vs manual. Risk of split-brain; use fencing/STONITH.
patroni / orchestrator promotes
Route read traffic to replicas to scale reads. Must handle replication lag (stale reads) and read-your-writes needs.
read preference: primary/secondary
Multiple nodes accept writes; conflicts resolved via LWW, vector clocks, or CRDTs. Complex but high write availability.
conflict resolution: LWW / vector clocks
Delay between primary commit and replica apply. Causes stale reads; monitor lag; route critical reads to primary.
SHOW REPLICA STATUS; -- Seconds_Behind_Source (MySQL 8.0.22+)
-- legacy: Seconds_Behind_Master
Physical: byte-level (WAL) replication, same version. Logical: row-level changes, supports different schemas/versions/filtering.
logical decoding → CDC
Stream DB changes to other systems (Kafka) for analytics/search. Based on WAL/logical replication.
Debezium reads WAL → Kafka
Two nodes both believe they are primary, causing divergent writes. Prevented by quorum, fencing, consensus (Raft/Paxos).
Distributed SQL uses consensus (Raft/Paxos) for leader election and committed log replication, enabling safety and automatic failover (Spanner, CockroachDB).
Raft: leader election + log replication
Quorum systems require W acks to write and R to read; strong consistency when R + W > N. Tunable per request (Cassandra, DynamoDB).
R + W > N → strong consistency
Sharding splits one DB across machines by a shard key for write scale. Partitioning splits within one DB (by range/list/hash).
shard key = user_id
Choose high cardinality, even distribution, and query-friendly (appears in predicates). Bad key → hot shards / scatter-gather.
good: user_id hash; bad: created_at range hot latest
Shard by value ranges. Good for range queries, but can create hot shards (latest range).
shards: [0,1000),[1000,2000)...
Hash key to shard. Even distribution but range queries become scatter-gather.
shard = hash(key) % N
One shard/key gets disproportionate traffic. Mitigate by salting, splitting, or caching.
salted key: user_id + random suffix
Expensive or unsupported. Design schema to keep related data on same shard (co-location) or handle in app.
Moving data when adding shards. Use consistent hashing or virtual shards (slots) to minimize movement.
16384 hash slots (Redis Cluster)
Query without shard key hits all shards and aggregates; slow. Design queries to include shard key.
Small lookup tables replicated to all shards to avoid cross-shard joins.
Replication scales reads and availability; sharding scales writes and storage. Often combined.
Maps keys to a ring; adding/removing a node moves about K/N keys (a 1/N fraction of the keys). Reduces rebalancing cost.
ring of virtual nodes
Partition a table by range/list/hash within one DB; planner prunes partitions. Improves maintenance and locality without cross-node sharding.
CREATE TABLE t (...) PARTITION BY RANGE (created_at);
EXPLAIN shows plan; EXPLAIN ANALYZE executes and shows actual timings/rows. Use to find scans, bad joins, sorts.
EXPLAIN ANALYZE SELECT ...;
Seq scan reads whole table; index scan uses index. Planner picks based on selectivity and cost. Small tables → seq scan fine.
When index covers query and visibility map allows, no heap fetch. Requires VACUUM upkeep (Postgres).
Loop issuing one query per item → N+1 queries. Fix with JOIN or IN/batch fetch.
-- instead of loop: SELECT ... WHERE id IN (...)
Nested loop (small), hash join (large equi-joins), merge join (sorted inputs). Planner chooses by cost.
ORDER BY not covered by index triggers sort (memory/disk). Add index matching ORDER BY to avoid.
OFFSET gets slower with depth (must scan/skip). Keyset (WHERE id > last) is O(log n) and stable.
WHERE id > :last ORDER BY id LIMIT 20
Precomputed query result stored as table; refresh manually/scheduled. Great for expensive aggregates.
CREATE MATERIALIZED VIEW mv AS SELECT ...; REFRESH MATERIALIZED VIEW mv;
Planner uses table stats (row counts, histograms). Stale stats → bad plans. Run ANALYZE after bulk changes.
ANALYZE table;
Plan cached for first parameter values may be suboptimal for others. Mitigate with OPTION (RECOMPILE) or plan guides.
INNER (matching rows), LEFT/RIGHT (keep one side), FULL (both), CROSS (cartesian), SELF (same table). Choose based on needed rows and null handling.
SELECT ... FROM a LEFT JOIN b ON ...
Compute over a row's window without collapsing rows (ROW_NUMBER, RANK, LAG/LEAD, SUM OVER). Useful for running totals and top-N per group.
SELECT *, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) FROM emp;
Common Table Expressions name subqueries for readability; recursive CTEs traverse hierarchies/graphs. May be inlined or materialized depending on engine.
WITH RECURSIVE tree AS (...) SELECT ...
Structured schema, joins, ACID transactions, strong consistency, mature tooling. Best for relational/transactional data.
Document (Mongo), KV (Redis/Dynamo), Column (Cassandra), Graph (Neo4j). Each optimized for specific access patterns.
During a network partition, choose Consistency or Availability. PACELC: if partitioned, trade C vs A; else trade latency vs consistency.
Partition: CP or AP
Else: latency vs consistency (PACELC)
NoSQL often BASE: Basically Available, Soft state, Eventual consistency. Opposite of ACID (approx).
Updates propagate asynchronously; reads may be stale but converge. Acceptable for feeds/likes, not balances.
Document stores nested objects, flexible schema, read locality. Relational normalizes, joins, strong constraints.
Massive scale, flexible/evolving schema, high write throughput, simple access patterns, geo-distribution.
Complex queries/joins, transactions across entities, strong consistency, reporting/analytics, mature ecosystem.
Use multiple DB types per need: SQL for transactions, Redis for cache, Mongo for catalogs, search engine for search.
Distributed SQL with horizontal scale + ACID (CockroachDB, Spanner). Best of both but operational complexity.
Store embeddings and support approximate nearest-neighbor search (HNSW, IVF) for semantic search/RAG; often paired with relational DB (polyglot).
CREATE INDEX ... USING hnsw (embedding vector_cosine_ops);
Reuse DB connections to avoid connect overhead. Size pool to DB capacity; too large causes contention. Heuristic starting point only—measure.
pool size ≈ (cores * 2) + effective_spindles -- HikariCP/PG heuristic
Writes to primary, reads to replicas. Handle lag and read-your-writes (route user's own reads to primary briefly).
Cache hot data (Redis) with TTL; invalidate on write or use cache-aside. Watch stampede/thundering herd.
cache-aside: read cache → miss → DB → set cache
Unique key per request stored; retry returns same result. Prevents duplicate writes on retries.
INSERT ... ON CONFLICT (idempotency_key) DO NOTHING
Mark deleted_at instead of deleting; preserves history/audit but complicates queries and uniqueness.
WHERE deleted_at IS NULL
Optimistic locking: version column; update only if version matches; retry on conflict. OCC: read → modify → write if version unchanged else retry; no locks held; conflicts detected at commit. Add version/updated_at column to detect concurrent modifications. Good for low contention.
UPDATE t SET v=v+1 WHERE id=? AND v=?
-- OCC: WHERE version = :expected
SELECT ... FOR UPDATE locks rows; prevents conflicts but reduces concurrency and risks deadlocks.
SELECT * FROM t WHERE id=? FOR UPDATE;
Versioned schema changes (Flyway/Liquibase). Backward-compatible, reversible, tested. Avoid long locks on large tables.
Regular backups + WAL archiving enable point-in-time recovery. Define RPO/RTO; test restores regularly.
RPO/RTO; restore test
Pooler between app and DB (transaction/statement pooling) reduces connections and overhead; watch prepared statements and session features.
pool_mode = transaction
RPO = max acceptable data loss (drives backup/WAL frequency); RTO = max acceptable downtime (drives restore/HA design). Test restores.
RPO: backup interval + WAL archiving
RTO: restore/failover time
Pessimistic locks rows upfront (safe, lower concurrency). Optimistic assumes no conflict, checks version at write (high concurrency, retries).
Lock in consistent order, keep transactions short, use timeouts, avoid user interaction mid-txn, retry on deadlock.
SET lock_timeout = '2s';
A txn repeatedly aborted/retried never progresses. Use backoff and priority/aging.
Serializable isolation prevents all but may abort; apps must retry serialization failures.
SQLSTATE 40001 → retry
Application-level locks in DB (pg_advisory_lock) for coordinating non-row resources.
SELECT pg_advisory_lock(42);
Row-level maximizes concurrency; table-level simpler but blocks more. Escalation may occur under load.
Lock gap between index records to prevent phantoms (InnoDB). Can cause unexpected blocking/deadlocks.
InnoDB: row lock + gap lock; prevents phantom inserts in range. Explains locking reads behavior.
MySQL default; transactional, MVCC, clustered PK, row-level locks, FK support, crash recovery via redo/undo logs.
Legacy MySQL engine; table-level locks, no transactions/FK, full-text. Largely replaced by InnoDB.
In-memory tables; very fast but volatile and table locks. Good for temp/lookup.
Log-Structured Merge tree: writes to memtable then SSTables; compaction. High write throughput (Cassandra/RocksDB/LevelDB).
write → memtable → SSTable → compaction
Read-optimized balanced tree (InnoDB, Postgres). Good point/range reads; writes update tree in place.
Stores by column; great for analytics (scans/aggregates) but poor for OLTP point updates.
Parquet / ClickHouse
Rows appended without order; PK index points to heap (Postgres). Updates create new tuple + vacuum.
Sequential log of changes for durability and crash recovery; enables group commit and replication.
Flush dirty pages to disk periodically so recovery doesn't replay entire log. Balances write amplification.
Reclaim space from dead tuples/SSTables. Postgres VACUUM; LSM compaction. Neglect → bloat/slowdown.
VACUUM ANALYZE;
Want this as flashcards? Study these 118 cards recall-first in the browser — flip, answer out loud, grade yourself.
What's new and the interview questions people are actually getting asked. No spam.