BTI Beyond The Interviews

Databases · 10 sections

Databases — Most Asked

ACID, indexing, replication and SQL-vs-NoSQL — the database questions backend rounds keep returning to.

Free · full sheet 118 cards Updated 24 Oct 2026

Fundamentals

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

ACID properties

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

Atomicity

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

Consistency

A transaction moves the DB from one valid state to another, preserving constraints (PK, FK, CHECK, triggers).

FK violations abort txn
CHECK constraints enforced

Isolation

Concurrent transactions behave as if serial. Real systems trade strictness for throughput via isolation levels.

SERIALIZABLE > REPEATABLE READ > READ COMMITTED > READ UNCOMMITTED

Durability

Once committed, data survives crashes/power loss via WAL flushed to disk (fsync) plus checkpoints.

commit → fsync(WAL) → durable
checkpoint → flush data pages later

1NF (First Normal Form)

Each column holds atomic (indivisible) values; no repeating groups; each row unique. Eliminates multi-valued attributes.

phone1,phone2 → phones table (1NF)

2NF

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)

3NF

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)

BCNF

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

Denormalization

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)

ER model basics

Entities (tables), attributes (columns), relationships (1:1, 1:N, M:N). M:N resolved via junction table.

students ⋈ enrollments ⋈ courses

Primary vs foreign key

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 semantics

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

Candidate vs super key

Super key uniquely identifies rows (may have extra attrs). Candidate key is minimal super key. One chosen as primary key.

OLTP vs OLAP

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

Indexing

What is an index?

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 vs B tree

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

Hash index

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

Composite (multi-column) index

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

Covering index

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 vs non-clustered

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

Primary key index

Usually clustered B+ tree on PK. In InnoDB table is organized by PK (clustered).

When an index hurts

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

Sargability

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

Index selectivity/cardinality

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

Partial/filtered index

Index only subset of rows matching a predicate; smaller and faster for common filtered queries.

CREATE INDEX ON orders(status) WHERE status='pending';

Transactions

Transaction states

Active → partially committed → committed; or failed → aborted → rolled back. Savepoints allow partial rollback.

BEGIN; ...; COMMIT/ROLLBACK;

Isolation levels

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

Dirty read

Reading uncommitted data from another txn that may rollback. Prevented by Read Committed and above.

Non-repeatable read

Re-reading same row returns different value because another txn committed an update between reads. Prevented by Repeatable Read+.

Phantom read

Re-running a range query returns new rows inserted by another committed txn. Prevented by Serializable (or gap locks).

Lost update

Two txns read same value, both write; one overwrites the other. Prevented by locking or optimistic versioning.

Write skew

Two txns read overlapping data and write disjoint subsets, violating constraint. Serializable or predicate locks needed.

MVCC

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

Lock types

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

Deadlock

Two txns each hold lock the other wants. DB detects and aborts one (victim) with deadlock error; app retries.

retry on SQLSTATE 40001 / deadlock

Savepoints

Named points inside a txn to rollback partially without aborting whole txn. Useful in nested operations.

SAVEPOINT sp1; ...; ROLLBACK TO sp1;

Two-phase commit (2PC)

Distributed txn protocol: prepare (vote) then commit. Ensures atomicity across nodes but blocking on coordinator failure.

prepare → vote → commit/abort

PostgreSQL Serializable (SSI)

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

Replication

Leader/follower (primary/replica)

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

Synchronous replication

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

Asynchronous replication

Leader commits without waiting; followers catch up. Fast writes but lag and possible loss on failover.

replication lag → stale reads

Semi-synchronous

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

Failover

On primary failure, promote a replica. Automatic vs manual. Risk of split-brain; use fencing/STONITH.

patroni / orchestrator promotes

Read replicas

Route read traffic to replicas to scale reads. Must handle replication lag (stale reads) and read-your-writes needs.

read preference: primary/secondary

Multi-master replication

Multiple nodes accept writes; conflicts resolved via LWW, vector clocks, or CRDTs. Complex but high write availability.

conflict resolution: LWW / vector clocks

Replication lag

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

Logical vs physical replication

Physical: byte-level (WAL) replication, same version. Logical: row-level changes, supports different schemas/versions/filtering.

logical decoding → CDC

CDC (Change Data Capture)

Stream DB changes to other systems (Kafka) for analytics/search. Based on WAL/logical replication.

Debezium reads WAL → Kafka

Split-brain

Two nodes both believe they are primary, causing divergent writes. Prevented by quorum, fencing, consensus (Raft/Paxos).

Consensus in distributed SQL

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

Read/write quorums

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

Sharding vs partitioning

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

Shard key selection

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

Range sharding

Shard by value ranges. Good for range queries, but can create hot shards (latest range).

shards: [0,1000),[1000,2000)...

Hash sharding

Hash key to shard. Even distribution but range queries become scatter-gather.

shard = hash(key) % N

Hotspot / hot key

One shard/key gets disproportionate traffic. Mitigate by salting, splitting, or caching.

salted key: user_id + random suffix

Cross-shard joins

Expensive or unsupported. Design schema to keep related data on same shard (co-location) or handle in app.

Resharding / rebalancing

Moving data when adding shards. Use consistent hashing or virtual shards (slots) to minimize movement.

16384 hash slots (Redis Cluster)

Scatter-gather

Query without shard key hits all shards and aggregates; slow. Design queries to include shard key.

Global tables / reference data

Small lookup tables replicated to all shards to avoid cross-shard joins.

Sharding vs replication

Replication scales reads and availability; sharding scales writes and storage. Often combined.

Consistent hashing

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

Declarative partitioning (Postgres)

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

Query Optimization

EXPLAIN / EXPLAIN ANALYZE

EXPLAIN shows plan; EXPLAIN ANALYZE executes and shows actual timings/rows. Use to find scans, bad joins, sorts.

EXPLAIN ANALYZE SELECT ...;

Seq scan vs index scan

Seq scan reads whole table; index scan uses index. Planner picks based on selectivity and cost. Small tables → seq scan fine.

Index-only scan

When index covers query and visibility map allows, no heap fetch. Requires VACUUM upkeep (Postgres).

N+1 problem

Loop issuing one query per item → N+1 queries. Fix with JOIN or IN/batch fetch.

-- instead of loop: SELECT ... WHERE id IN (...)

Join algorithms

Nested loop (small), hash join (large equi-joins), merge join (sorted inputs). Planner chooses by cost.

Sort / filesort

ORDER BY not covered by index triggers sort (memory/disk). Add index matching ORDER BY to avoid.

Pagination: OFFSET vs keyset

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

Materialized view

Precomputed query result stored as table; refresh manually/scheduled. Great for expensive aggregates.

CREATE MATERIALIZED VIEW mv AS SELECT ...; REFRESH MATERIALIZED VIEW mv;

Statistics & ANALYZE

Planner uses table stats (row counts, histograms). Stale stats → bad plans. Run ANALYZE after bulk changes.

ANALYZE table;

Parameter sniffing

Plan cached for first parameter values may be suboptimal for others. Mitigate with OPTION (RECOMPILE) or plan guides.

SQL JOIN types

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 ...

Window functions

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;

CTEs (WITH)

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 ...

NoSQL vs SQL

SQL (relational) strengths

Structured schema, joins, ACID transactions, strong consistency, mature tooling. Best for relational/transactional data.

NoSQL categories

Document (Mongo), KV (Redis/Dynamo), Column (Cassandra), Graph (Neo4j). Each optimized for specific access patterns.

CAP theorem

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)

BASE

NoSQL often BASE: Basically Available, Soft state, Eventual consistency. Opposite of ACID (approx).

Eventual consistency

Updates propagate asynchronously; reads may be stale but converge. Acceptable for feeds/likes, not balances.

Document vs relational

Document stores nested objects, flexible schema, read locality. Relational normalizes, joins, strong constraints.

When to choose NoSQL

Massive scale, flexible/evolving schema, high write throughput, simple access patterns, geo-distribution.

When to choose SQL

Complex queries/joins, transactions across entities, strong consistency, reporting/analytics, mature ecosystem.

Polyglot persistence

Use multiple DB types per need: SQL for transactions, Redis for cache, Mongo for catalogs, search engine for search.

NewSQL

Distributed SQL with horizontal scale + ACID (CockroachDB, Spanner). Best of both but operational complexity.

Vector databases

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

Common Patterns

Connection pooling

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

Read replica routing

Writes to primary, reads to replicas. Handle lag and read-your-writes (route user's own reads to primary briefly).

Caching layer

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

Idempotency keys

Unique key per request stored; retry returns same result. Prevents duplicate writes on retries.

INSERT ... ON CONFLICT (idempotency_key) DO NOTHING

Soft delete

Mark deleted_at instead of deleting; preserves history/audit but complicates queries and uniqueness.

WHERE deleted_at IS NULL

Optimistic locking

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

Pessimistic locking

SELECT ... FOR UPDATE locks rows; prevents conflicts but reduces concurrency and risks deadlocks.

SELECT * FROM t WHERE id=? FOR UPDATE;

Database migrations

Versioned schema changes (Flyway/Liquibase). Backward-compatible, reversible, tested. Avoid long locks on large tables.

Backup & PITR

Regular backups + WAL archiving enable point-in-time recovery. Define RPO/RTO; test restores regularly.

RPO/RTO; restore test

Connection poolers (PgBouncer)

Pooler between app and DB (transaction/statement pooling) reduces connections and overhead; watch prepared statements and session features.

pool_mode = transaction

Backup RPO/RTO

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

Concurrency Control

Pessimistic vs optimistic

Pessimistic locks rows upfront (safe, lower concurrency). Optimistic assumes no conflict, checks version at write (high concurrency, retries).

Deadlock prevention

Lock in consistent order, keep transactions short, use timeouts, avoid user interaction mid-txn, retry on deadlock.

SET lock_timeout = '2s';

Livelock / starvation

A txn repeatedly aborted/retried never progresses. Use backoff and priority/aging.

Serialization anomalies

Serializable isolation prevents all but may abort; apps must retry serialization failures.

SQLSTATE 40001 → retry

Advisory locks

Application-level locks in DB (pg_advisory_lock) for coordinating non-row resources.

SELECT pg_advisory_lock(42);

Row-level vs table-level locks

Row-level maximizes concurrency; table-level simpler but blocks more. Escalation may occur under load.

Gap locks

Lock gap between index records to prevent phantoms (InnoDB). Can cause unexpected blocking/deadlocks.

Next-key locks

InnoDB: row lock + gap lock; prevents phantom inserts in range. Explains locking reads behavior.

Storage Engines

InnoDB

MySQL default; transactional, MVCC, clustered PK, row-level locks, FK support, crash recovery via redo/undo logs.

MyISAM

Legacy MySQL engine; table-level locks, no transactions/FK, full-text. Largely replaced by InnoDB.

Memory engine

In-memory tables; very fast but volatile and table locks. Good for temp/lookup.

LSM tree

Log-Structured Merge tree: writes to memtable then SSTables; compaction. High write throughput (Cassandra/RocksDB/LevelDB).

write → memtable → SSTable → compaction

B+ tree engine

Read-optimized balanced tree (InnoDB, Postgres). Good point/range reads; writes update tree in place.

Columnar storage

Stores by column; great for analytics (scans/aggregates) but poor for OLTP point updates.

Parquet / ClickHouse

Heap (unordered) storage

Rows appended without order; PK index points to heap (Postgres). Updates create new tuple + vacuum.

WAL (redo log)

Sequential log of changes for durability and crash recovery; enables group commit and replication.

Checkpoint

Flush dirty pages to disk periodically so recovery doesn't replay entire log. Balances write amplification.

Vacuum / compaction

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.

Open the card deck