12.1 Indexing Strategies
| Index Type | Structure | Best For | Notes |
|---|---|---|---|
| B-tree | Balanced tree, sorted keys | Range queries, equality, sorting (<, >, BETWEEN, ORDER BY) |
Default index type in virtually every RDBMS |
| Hash | Hash table of key → row pointer | Pure equality lookups (=) |
Cannot support range scans or sorting; PostgreSQL/MySQL support explicitly, mostly niche now that B-tree equality lookups are nearly as fast |
| GIN (Generalized Inverted Index) | Inverted index — maps each element (e.g., array element, JSON key, lexeme) to the rows containing it | Full-text search (tsvector), JSONB containment (@>), array membership |
PostgreSQL-specific; slower to build/update than B-tree, very fast for containment queries |
| GiST | Generalized balanced tree supporting custom operators | Geometric data, range types, full-text (alternative to GIN), nearest-neighbor | PostgreSQL; used heavily by PostGIS |
| BRIN (Block Range Index) | Stores min/max per block range | Very large, naturally ordered tables (time-series by insert order) | Tiny index size, good for append-only tables where physical order correlates with the indexed column |
| Bitmap | Bitmap per distinct value | Low-cardinality columns in analytical/OLAP queries | Common in data warehouses (Oracle, Redshift), not typically a manually-created index type in OLTP engines |
-- Clustered Index (one per table — determines physical row order)
CREATE CLUSTERED INDEX IX_Orders_CreatedAt ON Orders(CreatedAt DESC);
-- Non-Clustered covering index — avoids a key lookup back to the clustered index
CREATE NONCLUSTERED INDEX IX_Orders_CustomerId
ON Orders(CustomerId)
INCLUDE (Status, Total)
WHERE Status = 'Active'; -- filtered index: smaller, faster
-- Composite index — column order matters!
CREATE INDEX IX_Orders_Status_Date ON Orders(Status, CreatedAt DESC);
-- Helps: WHERE Status = 'Active' ORDER BY CreatedAt DESC
-- Does NOT help as well: WHERE CreatedAt > '2024-01-01' (Status is the leading column)
-- PostgreSQL GIN index on JSONB
CREATE INDEX idx_events_data ON events USING GIN (data);
SELECT * FROM events WHERE data @> '{"status": "completed"}';
When to index: columns in WHERE/JOIN/ORDER BY clauses with high selectivity. When not to: low-cardinality columns (a 3-value Status column is a scan regardless), columns updated very frequently (index maintenance cost), or tiny tables (< ~1000 rows — a scan is faster than an index seek).
12.2 Query Optimization Patterns
-- N+1 problem — the classic ORM trap
-- ❌ BAD: one query per order to fetch its items
SELECT * FROM Orders;
-- then, per order: SELECT * FROM OrderItems WHERE OrderId = @orderId;
-- ✅ GOOD: single JOIN
SELECT o.Id, o.Total, oi.ProductId, oi.Quantity
FROM Orders o JOIN OrderItems oi ON o.Id = oi.OrderId
WHERE o.CustomerId = @customerId;
-- Sargability — functions on indexed columns defeat the index
-- ❌ BAD
SELECT * FROM Orders WHERE YEAR(CreatedAt) = 2024;
-- ✅ GOOD (sargable — index on CreatedAt can be used)
SELECT * FROM Orders WHERE CreatedAt >= '2024-01-01' AND CreatedAt < '2025-01-01';
-- Pagination — keyset (cursor) beats OFFSET at scale
-- ❌ SLOW for large offsets — DB still scans/discards the first 100,000 rows
SELECT * FROM Orders ORDER BY Id OFFSET 100000 ROWS FETCH NEXT 20 ROWS ONLY;
-- ✅ FAST — index seek straight to the right spot
SELECT TOP 20 * FROM Orders WHERE Id > @lastSeenId ORDER BY Id;
Execution plan operators to know:
| Operator | Meaning | Concern |
|---|---|---|
| Table Scan | Reads every row | Missing index on the filter column |
| Index Scan | Reads the entire index | Index exists but isn’t selective enough for this predicate |
| Index Seek | B-tree traversal directly to matching rows | Good — efficient |
| Key Lookup | Goes back to the clustered index for extra columns | Add those columns via INCLUDE to make the index covering |
| Hash Join | Builds an in-memory hash table for the join | Normal/expected for large unsorted datasets |
| Nested Loop | For each outer row, scans the inner input | Fine for small inputs, expensive for large ones |
| Sort | Explicit sort step | Consider an index that pre-sorts the data instead |
12.3 Normalization vs Denormalization
| Normal Form | Rule | Example Violation |
|---|---|---|
| 1NF | Atomic values, no repeating groups | A column holding "tag1,tag2,tag3" |
| 2NF | No partial dependency on part of a composite key | OrderItem.CustomerName depending only on OrderId, not the full (OrderId, ProductId) key |
| 3NF | No transitive dependency | Order.CustomerCity depends on CustomerId, not directly on OrderId |
| BCNF | Every determinant is a candidate key | Edge case of 3NF with multiple overlapping candidate keys |
When to denormalize deliberately: read-heavy workloads where JOIN cost dominates; reporting/analytics queries; caching pre-computed aggregations; document-style access patterns where you want to read one entity plus all its related data in a single round trip. Denormalization is a conscious tradeoff — you accept write-side complexity (keeping duplicated data in sync) in exchange for read-side speed and simplicity.
12.4 Transaction Isolation Levels — Anomalies Table
| Level | Dirty Reads | Non-Repeatable Reads | Phantom Reads | Locking Behavior |
|---|---|---|---|---|
| Read Uncommitted | Yes | Yes | Yes | None — fastest, reads in-flight uncommitted data |
| Read Committed (most DBs’ default) | No | Yes | Yes | Shared lock held only during the individual read |
| Read Committed Snapshot (RCSI) | No | Yes | Yes | Row versioning instead of locks — no reader/writer blocking |
| Repeatable Read | No | No | Yes | Shared locks held until transaction commit |
| Snapshot | No | No | No | Row versioning — each transaction sees a consistent snapshot |
| Serializable | No | No | No | Range locks — strongest, slowest, fully serial-equivalent behavior |
Anomaly definitions:
- Dirty read: transaction reads data another transaction has written but not yet committed (which might later roll back).
- Non-repeatable read: a transaction reads the same row twice and gets different values because another transaction updated and committed it in between.
- Phantom read: a transaction re-runs a range query and finds new rows that another transaction inserted and committed in between.
Interview-ready line: “In production, I typically enable RCSI on SQL Server (or rely on PostgreSQL’s MVCC, which gives similar behavior by default). It eliminates reader-writer blocking via row versioning in tempdb, giving better concurrency than Read Committed’s locking without the complexity of full Snapshot isolation.”
public async Task ExecuteWithDeadlockRetryAsync(Func<Task> action, int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
try { await action(); return; }
catch (SqlException ex) when (ex.Number == 1205 && i < maxRetries - 1)
{
await Task.Delay(Random.Shared.Next(50, 200)); // jittered backoff
}
}
}
12.5 Interview Q&A
Q1: A table has 100M rows and queries are slow. How do you diagnose and fix it?
Check the execution plan first — look for table scans, key lookups, and sort operators. Check for missing indexes (SQL Server’s
sys.dm_db_missing_index_details). Check statistics freshness — stale stats cause bad plans, refresh withUPDATE STATISTICS. Rewrite non-sargable predicates and eliminateSELECT *. Consider range partitioning if queries commonly filter by date. Add covering indexes withINCLUDEto eliminate key lookups. Check for parameter sniffing (a plan cached for one skewed parameter value being reused badly for others) — mitigate withOPTIMIZE FORorRECOMPILEhints. Finally, look at wait stats to determine if the bottleneck is actually CPU, I/O, or memory rather than the query itself.
Q2: Explain transaction isolation levels and the anomalies they prevent.
Read Uncommitted allows dirty reads, non-repeatable reads, and phantoms — fastest, essentially no isolation. Read Committed (most databases’ default) prevents dirty reads but still allows non-repeatable reads and phantoms. Repeatable Read additionally prevents non-repeatable reads by holding shared locks until commit, but phantoms can still appear. Serializable prevents all three via range locking, at the cost of the most contention. In practice I favor snapshot-based isolation (RCSI on SQL Server, or PostgreSQL’s default MVCC behavior) over locking-based Repeatable Read/Serializable when the workload is read-heavy, because row versioning avoids reader/writer blocking entirely while still giving each transaction a consistent view.
Q3: How would you implement multi-tenancy at the database level?
Three approaches on a spectrum of isolation vs cost. Shared database/shared schema with a
TenantIdcolumn — cheapest, but risks a noisy neighbor and requires disciplined query filtering (a global query filter in the ORM helps prevent accidental cross-tenant leaks). Shared database/separate schemas per tenant — better isolation, but migrations must run per schema. Separate databases per tenant — maximum isolation and the easiest compliance story (a GDPR delete request is just “drop the database”), at the highest cost and connection-pool management complexity. I’d default to shared-schema with a mandatory global query filter for most SaaS products, and reserve separate databases for enterprise tiers with contractual isolation requirements.
Q4: Describe your approach to database migrations in a CI/CD pipeline.
Version-controlled, code-first migrations (EF Core Migrations, FluentMigrator, Flyway/Liquibase depending on stack) run as a pre-deployment step or init container, never manually. Every migration must be idempotent and backward-compatible with the previous application version, because during a rolling deploy old and new app code run against the same schema simultaneously. I use the expand-contract pattern for anything that looks like a rename or type change: add the new column, backfill it, deploy app code that writes to both and reads from the new one, verify, then drop the old column in a later migration. Every “up” migration should have a corresponding rollback, and I test migrations against a production-sized copy of data beforehand and alert if a migration exceeds a time budget (a sign it’s about to take a lock on a huge table).