HTHyperTransformer AI

Study cards › Databases

DatabasesInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is a JOIN?

Answer

A JOIN combines rows from two or more tables based on a related column. Types: INNER (only matches), LEFT (all rows from left, NULL where no match on right), RIGHT (mirror), FULL OUTER (everything from both sides), and CROSS (every combination). The right join is foundational to relational thinking.

Question

INNER JOIN vs LEFT JOIN?

Answer

INNER JOIN keeps only rows that have a match on both sides — like an intersection. LEFT JOIN keeps every row from the left table, filling NULL for missing matches on the right — useful when you want a list with optional related data (e.g. users and their last order, where some users have no orders).

Question

What is a database index?

Answer

An index is a separate data structure (usually a B-tree) that speeds up lookups by key. It's like the index at the back of a book — instead of scanning every page, you jump straight to where you need. Indexes speed reads but slightly slow writes (the index also needs updating).

Question

What is a composite index?

Answer

A composite index covers multiple columns in a specific order, e.g. (user_id, created_at). The order matters: queries that filter on user_id can use the index; ones filtering only on created_at can't. Always lead with the most selective column you query equality on.

Question

What is a covering index?

Answer

A covering index contains every column a query needs, so the database can answer the query from the index alone without touching the table itself. Massive speedup for hot read paths. In Postgres, use INCLUDE to add 'payload' columns to an index without making it part of the key.

Question

What is database normalization?

Answer

Normalization organizes data to reduce redundancy via 1NF (atomic columns), 2NF (no partial key dependencies), 3NF (no transitive dependencies). Each fact lives in one place. Reduces update anomalies but increases the number of JOINs you need to assemble information for queries.

Question

What is denormalization?

Answer

Denormalization intentionally duplicates data — like storing the user's name on every order — to speed up reads. Tradeoff: faster queries, harder writes (you must update many places to keep them consistent). Often used in analytics, NoSQL document design, and high-read OLTP workloads.

Question

What is a transaction?

Answer

A transaction is a unit of work executed atomically — either every statement commits, or every change is rolled back. Wrap related writes in BEGIN…COMMIT/ROLLBACK so partial failures don't leave the DB in an inconsistent state. Backbone of ACID guarantees.

Question

What is ACID?

Answer

ACID = Atomicity, Consistency, Isolation, Durability. Atomicity (all-or-nothing), Consistency (txn moves DB from one valid state to another), Isolation (concurrent txns don't see each other's partial work), Durability (once committed, data survives crashes). The four core promises of a relational DB.

Question

Each ACID property in plain English?

Answer

Atomicity: all your INSERTs go through, or none do. Consistency: rules (constraints, foreign keys) are never violated. Isolation: two simultaneous transactions can't trip over each other's half-finished work. Durability: once your COMMIT returns, the data is safe even if the server crashes.

Question

What is query optimization?

Answer

Improving the performance of a SQL query. Tactics: add the right indexes, rewrite joins, avoid SELECT *, filter early (push WHERE before JOIN where possible), use EXPLAIN to see the plan, and tune statistics. Optimization should always start with measurement, not guessing.

Question

What is EXPLAIN?

Answer

EXPLAIN shows the database's query plan — which tables it scans, in what order, using which indexes, with estimated row counts. EXPLAIN ANALYZE actually runs the query and gives real numbers. It's the single most important tool when a query is slow — read the plan, not the schema.

Question

What is a window function?

Answer

A window function computes a value across a related set of rows for each row, without collapsing them like GROUP BY does. Examples: ROW_NUMBER, RANK, LAG, SUM() OVER (PARTITION BY user_id). Powerful for analytics, running totals, deduplication, and 'previous row' calculations.

Question

ROW_NUMBER vs RANK vs DENSE_RANK?

Answer

All three number rows by order. ROW_NUMBER assigns a unique sequence (1,2,3…). RANK gives ties the same number but skips the next (1,1,3). DENSE_RANK gives ties the same number with no skip (1,1,2). Use them based on whether ties should share a position and whether you want gaps.

Question

What is a stored procedure?

Answer

A stored procedure is code (SQL/PLpgSQL/PLSQL) that lives inside the database and is callable from clients. Encapsulates logic close to the data — fast, less round-trips — but couples your app to the DB and is harder to version-control than app code. Use sparingly today.

Question

What is a database lock?

Answer

A lock is a mechanism that controls concurrent access to data. Shared (read) locks let many readers in; exclusive (write) locks are held by one writer at a time. Locks can be at row, page, or table level. Long locks cause contention and even deadlocks — keep transactions short.

Question

What is a deadlock and how do you handle it?

Answer

A deadlock is when two transactions wait on each other's locks — neither can proceed. The DB detects the cycle and kills one (the 'victim') with an error. Mitigate by acquiring locks in a consistent order, keeping transactions short, retrying on deadlock, and adding indexes to reduce lock scope.

Question

What is partitioning?

Answer

Partitioning splits a big table into smaller chunks (by range, list, or hash) within the same DB instance. Each chunk is queried/managed independently, improving performance for large tables and making it easier to drop old data (just drop a partition). Used heavily in time-series and analytics.

Question

Partitioning vs sharding?

Answer

Partitioning is one database splitting a single table internally — same instance. Sharding spreads data across MULTIPLE database instances — true horizontal scale. Partitioning is the simpler, easier step; sharding adds operational complexity (routing, cross-shard queries) but unlocks massive scale.

Question

What is PostgreSQL?

Answer

PostgreSQL is a powerful open-source relational database. It supports strict SQL standards, advanced features like MVCC, JSONB, full-text search, GIS, and extensions (pgvector, TimescaleDB, PostGIS). Often described as the 'reliable default' for new projects unless you have a specific reason to choose otherwise.

Question

Postgres optimization tips?

Answer

Tune work_mem and shared_buffers for your workload, add proper indexes (and drop unused ones), run VACUUM (autovacuum) regularly, keep transactions short to limit MVCC bloat, use EXPLAIN ANALYZE before guessing, enable pg_stat_statements to find slow queries, and use connection pooling (PgBouncer).

Question

What is database replication?

Answer

Replication copies data from a primary node to replicas, enabling read scaling and failover. Postgres uses streaming WAL (write-ahead log) replication. Replicas typically lag the primary slightly — beware reading your own writes from a replica immediately after writing.

Question

What's master-replica read scaling?

Answer

Writes go to the primary; reads can be served by replicas, multiplying read capacity. Watch out for replication lag — a user who just made a write may read stale data from a replica. Common patterns: pin recent writers to primary, or use synchronous replication for critical reads.

Question

What is JSONB in Postgres?

Answer

JSONB stores JSON in a binary format with support for indexing (GIN) and rich operators (->>, @>, jsonb_set). It lets you store semi-structured data without a separate document DB. Often the right choice when only some fields are dynamic and the rest fit cleanly into columns.

Question

What is MongoDB?

Answer

MongoDB is a document-oriented NoSQL database. Records are BSON documents (binary JSON) organized into collections. Schema is flexible — different docs in the same collection can have different fields. Built-in horizontal sharding and replica sets make it scale for write-heavy or rapidly-evolving schemas.

Question

MongoDB aggregation pipeline?

Answer

Mongo's aggregation pipeline is a series of stages ($match, $group, $project, $lookup, $unwind) that transform documents. It's Mongo's analog to SQL — you compose operations and the engine optimizes the pipeline. Useful for reports, joins between collections, and complex transformations server-side.

Question

MongoDB schema design tips?

Answer

Embed data that's accessed together in the same document (avoids joins, fast reads). Reference data accessed independently (avoids duplication). Design for your query patterns, not for normalization. Document size limit is 16MB, so unbounded arrays should be a separate collection.

Question

What is sharding in MongoDB?

Answer

Sharding distributes a collection across multiple shards based on a shard key. Choose a shard key with high cardinality and even write distribution (e.g. user_id is usually good; created_at is usually bad — all new writes hit one shard). The mongos router handles routing for you.

Question

What is Redis?

Answer

Redis is an in-memory key-value store with rich data structures: strings, lists, sets, hashes, sorted sets (ZSET), streams, geo indexes, and pub/sub. Sub-millisecond latency, single-threaded simplicity. Used everywhere as cache, session store, rate limiter, job queue backend, and leaderboard engine.

Question

Common Redis use cases?

Answer

Caching (the obvious one — DB query results, computed values), rate limiting per user/IP, session storage shared across app instances, leaderboards via sorted sets, pub/sub for real-time fan-out, job queues (BullMQ, RQ), and distributed locks for short-lived coordination.

Question

What is Redis pub/sub?

Answer

Pub/sub is a fire-and-forget messaging primitive: subscribers listen to channels, publishers send messages to channels. No persistence — if no one's listening, the message is lost. Great for real-time fan-out (notifications, live updates) but not a job queue replacement.

Question

How does Redis store sessions?

Answer

You store the session ID as the key and the serialized user data (JSON) as the value, with an EXPIRE to TTL the session. Any app instance can read it because Redis is shared — making your app stateless and easy to scale horizontally. Used by every major web framework's session middleware.

Question

How do you rate-limit with Redis?

Answer

Simplest: INCR a key like rate:user:123, set EXPIRE 60 the first time, reject if the value exceeds the limit. For smoother behavior, use a sliding window with sorted sets (ZADD timestamps, ZRANGEBYSCORE to count) or token-bucket scripts via Lua.

Question

What is a vector database?

Answer

A vector DB stores and searches high-dimensional embedding vectors by similarity (cosine, dot product, L2 distance). It's specialized for nearest-neighbor search, which traditional DBs don't do well. Used in RAG and semantic search, where you embed text/images and find 'most similar' results.

Question

What is Pinecone?

Answer

Pinecone is a fully managed cloud vector database aimed at AI/RAG. It handles ANN indexing, scaling, metadata filtering, hybrid search, and namespaces (multi-tenancy) — you just call its API. Trade-off: vendor lock-in and cost, but very low operational overhead.

Question

What is Weaviate?

Answer

Weaviate is an open-source vector database with built-in vectorizer modules (you can pass text and it embeds), hybrid search (vector + BM25), and a GraphQL-like query language. Self-hostable or cloud-managed. Good fit if you want control over the embedding pipeline.

Question

What is ChromaDB?

Answer

ChromaDB is a lightweight, open-source embedding database designed for AI app prototyping. It runs in-process or as a server and has a simple Python API. Great for local development and small-to-medium RAG apps; not the right choice for billion-vector production workloads.

Question

What is pgvector?

Answer

pgvector is a Postgres extension that adds a vector data type and approximate nearest-neighbor indexes (IVFFlat, HNSW). It lets you do vector search alongside relational queries in plain SQL — meaning one database, one transaction model, one toolchain. Often the right pragmatic choice if you already run Postgres.

Question

What is approximate nearest neighbor (ANN)?

Answer

ANN is fast similarity search that trades exactness for speed — you get the top-K nearest vectors with very high (but not perfect) recall. Exact search is O(N) and unusable at scale; ANN algorithms (HNSW, IVF, ScaNN) handle billions of vectors in milliseconds.

Question

What is HNSW?

Answer

Hierarchical Navigable Small World — a graph-based ANN index where layers of progressively denser graphs let you navigate quickly to the neighborhood and then find exact nearest neighbors locally. Excellent recall/latency tradeoffs, but more memory-hungry than IVF. The default in many vector DBs today.

Question

What are embeddings?

Answer

Embeddings are fixed-length numeric vectors that represent semantic meaning of text, images, audio, or code. Similar items end up close together in the vector space. Generated by models like OpenAI text-embedding-3-small, cohere-embed, or open-source ones like bge and e5.

Question

What is a primary key?

Answer

A primary key is a column (or set of columns) that uniquely identifies each row in a table. Implicitly indexed, never NULL, never duplicated. Choose between auto-increment integers, UUIDs (globally unique), or natural keys based on your needs (debugging, distribution, security).

Question

What's the purpose of a foreign key?

Answer

A foreign key enforces referential integrity — a value in one table must exist as a primary key in another. Prevents orphan rows (an order pointing to a non-existent user) at the database level, so even a buggy app can't violate the relationship. You can also CASCADE deletes/updates.

Question

WHERE vs HAVING?

Answer

WHERE filters individual rows BEFORE aggregation. HAVING filters groups AFTER aggregation. Example: WHERE country='US' picks US rows; HAVING COUNT(*) > 10 keeps only groups with more than 10 rows. Both can appear in the same query.

Question

What is a CTE?

Answer

A Common Table Expression is a named, temporary result set defined with WITH at the top of a query. Improves readability by breaking complex queries into steps. CTEs can also be recursive (great for tree/graph traversal in SQL) and may or may not be optimized as inline views depending on the DB.

Question

What is a materialized view?

Answer

A materialized view is a view whose result is physically stored on disk and periodically refreshed. Reading is as fast as querying a table, but the data is only as fresh as the last refresh. Great for expensive aggregations you query often and can tolerate slight staleness on.

Question

What is transaction isolation level?

Answer

Isolation levels control how much one transaction sees of others' partial work. From weakest to strongest: READ UNCOMMITTED, READ COMMITTED (Postgres default), REPEATABLE READ, SERIALIZABLE. Higher isolation = fewer anomalies but more contention and overhead. Most apps run at READ COMMITTED or REPEATABLE READ.

Question

What is a dirty read?

Answer

Reading another transaction's uncommitted changes — meaning you might read data that gets rolled back. Only allowed at READ UNCOMMITTED. Almost every database prevents this by default (READ COMMITTED and above).

Question

What is a phantom read?

Answer

A repeated query inside the same transaction returns NEW rows because another transaction inserted them. Prevented at SERIALIZABLE isolation. Subtle but matters for things like 'count all matching rows then do X based on the count'.

Question

What is MVCC?

Answer

Multi-Version Concurrency Control — readers see a consistent snapshot of the data at the moment the transaction started, while writers create new versions of rows without blocking readers. The DB cleans up old versions later (VACUUM in Postgres). Lets reads and writes happen concurrently without locks.

Question

What is VACUUM in Postgres?

Answer

VACUUM reclaims space from dead row versions left behind by MVCC, prevents transaction ID wraparound, and updates statistics. Autovacuum handles it in the background, but high-update tables sometimes need manual tuning. Skipping VACUUM leads to bloat — tables and indexes growing far larger than their actual data.

Question

What is a B-tree index?

Answer

A B-tree is a balanced tree structure where each node holds many keys, supporting equality lookups and range scans in O(log n). It's the default index type in most databases — works for =, <, >, BETWEEN, ORDER BY, and prefix searches like LIKE 'foo%'.

Question

What is a hash index?

Answer

A hash index is optimized for equality lookups: hash the key and jump to the bucket. Doesn't support range queries (<, >, BETWEEN, ORDER BY). Useful for very large tables where you only do =. Rarely beats a B-tree in practice; most teams stick with B-trees for flexibility.

Question

When should you NOT add an index?

Answer

On tiny tables (full scan is fine), on columns with very low cardinality (a boolean has 2 values — index doesn't help), or on columns updated heavily relative to reads (every write must also update the index). Track unused indexes — they cost space and write speed for no benefit.

Question

Clustered vs non-clustered index?

Answer

A clustered index stores the table rows physically in index order — only one per table. Lookups are very fast because the data IS the index. Non-clustered indexes are separate structures pointing back to the table. MySQL's InnoDB clusters on the primary key; Postgres doesn't have classic clustered indexes.

Question

OLTP vs OLAP?

Answer

OLTP: many small transactions per second (orders, signups, updates) — optimized for fast row-level reads/writes. OLAP: large analytical queries scanning millions of rows for reports and BI — optimized for columnar reads. Usually different systems entirely (OLTP in Postgres, OLAP in Snowflake/BigQuery).

Question

What is a data warehouse?

Answer

A data warehouse is a system optimized for analytical queries on historical data — columnar storage, denormalized star schemas, massively parallel execution. Examples: Snowflake, BigQuery, Redshift, ClickHouse. You typically ETL or stream data from OLTP systems into the warehouse for analytics.

Question

Columnar vs row-oriented storage?

Answer

Row stores keep entire rows together — fast for OLTP where you read whole records. Column stores keep each column together — fast for analytics where you scan a few columns across millions of rows. Same data, very different layout and access patterns; right tool for the right job.

Question

What is upsert?

Answer

Upsert = insert if the row doesn't exist, otherwise update. In SQL: INSERT … ON CONFLICT (key) DO UPDATE …. In Mongo: updateOne with upsert: true. Useful for idempotent writes — repeating the same operation produces the same result.

Question

What are database constraints?

Answer

Rules enforced by the DB itself: NOT NULL (column can't be empty), UNIQUE (no duplicates), CHECK (custom predicate), FOREIGN KEY (must reference an existing row), PRIMARY KEY (unique + not null). Catch bad data at the lowest layer — never trust application code alone.

Question

What is a sequence?

Answer

A sequence is a DB object that generates monotonically increasing numbers (1, 2, 3…). Postgres SEQUENCEs power SERIAL/IDENTITY primary keys. Sequences are safe under concurrency (each call atomically increments) but values can have gaps after rollbacks — that's normal.

Question

When should you use UUIDs as primary keys?

Answer

When IDs must be globally unique without a central coordinator (distributed systems, client-generated IDs), non-guessable (URLs, security), or merged across DBs. Downsides: larger (16 bytes vs 4-8), slower index lookups, and worse data locality. UUIDv7 mitigates the locality issue by being time-ordered.

Question

What is connection pooling at the DB layer?

Answer

Tools like PgBouncer or AWS RDS Proxy sit between your app and the DB, multiplexing many app connections onto fewer real DB connections. Without it, Postgres can drown under thousands of clients (each connection costs significant memory). Essential at scale.

Question

What is read replica lag?

Answer

The time between a write committing on primary and being visible on a replica. Usually milliseconds, but spikes during high write load. Beware reading your own writes from a replica immediately — patterns to handle: pin recent writers, read from primary for critical paths, or wait for replication.

Question

What is the write-ahead log (WAL)?

Answer

The WAL is an append-only log of all changes, written to disk BEFORE the change hits the actual data files. On crash, the DB replays the WAL to recover. It also powers replication: stream the WAL to replicas and they reconstruct the same state. Foundation of durability.

Question

How does deadlock detection work?

Answer

The DB tracks a 'wait-for' graph of which transactions are waiting on which locks. When a cycle is detected, one transaction (the victim, often the cheapest to roll back) is killed with a serialization error. Your app should catch this and retry the transaction.

Question

What is a covering index in Postgres?

Answer

A Postgres index with INCLUDE columns that aren't part of the index key but are stored alongside, so queries can be answered from the index alone — no heap lookup. Speeds up read-heavy workloads at the cost of slightly larger indexes.

Question

What is a GIN index?

Answer

Generalized Inverted Index — Postgres index type great for searching inside composite values: full-text search (tsvector), JSONB containment, and array elements. Each indexed value stores pointers to all rows containing it.

Question

What is a GiST index?

Answer

Generalized Search Tree — Postgres index framework for geospatial data (PostGIS), range types, and similarity queries (pg_trgm fuzzy text). More flexible than B-tree at the cost of being slower for simple equality lookups.

Question

What is a Postgres trigger?

Answer

A trigger is a function the DB automatically runs in response to INSERT, UPDATE, or DELETE on a table. Useful for audit logs, derived columns, or cross-table consistency. Use sparingly — hidden logic in triggers is notoriously hard to debug compared to explicit application code.

Question

What is database schema migration?

Answer

Versioned, ordered changes to the schema (add column, create index, alter table) checked into source control and applied via tools like Flyway, Liquibase, Prisma Migrate, Alembic, or Knex. Every env runs the same migrations in the same order — no manual ALTER TABLE in production.

Question

What is a zero-downtime migration?

Answer

Schema changes that don't lock or block production traffic. Pattern for renaming a column: add new column, dual-write, backfill, switch reads, drop old column — over multiple deploys. Big tables need especially careful planning (don't add a NOT NULL DEFAULT to a billion rows in one statement).

Question

What are the principles for choosing a shard key?

Answer

High cardinality (lots of distinct values), even distribution (no hotspots), and ideally queried together (so queries hit few shards). Bad choices cause hot shards or expensive cross-shard scatter queries. The shard key is usually the hardest decision in a sharded design — get it right early.

Question

Consistency models in NoSQL?

Answer

Strong (you always read the latest value), eventual (you might read stale data briefly, but it converges), or tunable per request (DynamoDB's strongly_consistent flag; Cassandra's QUORUM/ONE). Pick the right model per access pattern — not everything needs strong consistency.

Question

What is a tombstone?

Answer

In eventually-consistent stores like Cassandra, a delete writes a 'tombstone' marker rather than removing the row immediately. The marker propagates to all replicas, then compaction sweeps both. Without tombstones, a stale replica could resurrect deleted data when it came back online.

Question

What is compaction?

Answer

Compaction merges on-disk data files to reclaim space and improve read efficiency. Common in LSM-tree stores (Cassandra, RocksDB, LevelDB). Compaction is a background process — when it gets behind, reads slow down and disk usage balloons.

Question

LSM-tree vs B-tree?

Answer

B-trees do in-place updates — balanced reads and writes, used in most relational DBs. LSM-trees buffer writes in memory, flush sorted files to disk, and compact them later — write-optimized, slower reads. Cassandra, RocksDB, Bigtable use LSM. Different tradeoffs for different workloads.

Question

What is third normal form (3NF)?

Answer

3NF rule: every non-key column depends on the key, the whole key, and nothing but the key. No transitive dependencies (don't store user_country derived from user_id in the same table). Most OLTP designs aim for 3NF, then selectively denormalize for performance.

Question

Denormalization in NoSQL?

Answer

Design documents to match access patterns — embed related data so a single read returns everything the consumer needs. The price is duplication and harder updates. In NoSQL, normalization isn't the default goal; serving queries efficiently is.

Question

TRUNCATE vs DELETE?

Answer

DELETE removes rows one by one — logged, transactional, can be rolled back, fires triggers, slow on huge tables. TRUNCATE drops and recreates the table's data files — much faster, less logging, but resets sequences and may not fire triggers. Use TRUNCATE for purging test data, never for selective deletes.

Question

What is SQL injection?

Answer

SQL injection happens when an attacker embeds malicious SQL via unsanitized user input (e.g. "' OR 1=1 --"). The classic remedy is parameterized queries (or ORMs) — user input is bound as a value, never interpolated into the SQL string. NEVER concatenate user input into queries.

Question

Unique constraint vs unique index?

Answer

Logically equivalent in most databases — both prevent duplicates. A UNIQUE constraint is enforced by an underlying unique index, so they're effectively the same thing under the hood. Use constraints in schema definitions for clarity; the index is what does the work.

Question

How do you find slow queries in Postgres?

Answer

Enable pg_stat_statements — it tracks total time, mean time, and call counts per query. Sort by total_time to find the queries costing you most. For one-off investigation, EXPLAIN ANALYZE shows the plan and actual timings. auto_explain logs slow queries automatically.

Question

When should you cache vs index?

Answer

Index when queries are predictable, frequent, and hit a small subset of rows efficiently. Cache when the computation is expensive (joins, aggregations, derived values), reads vastly outnumber writes, and you can tolerate slight staleness. Often you want both layers.

Question

Read-through vs write-through cache?

Answer

Read-through: the cache fetches from the DB on a miss, transparent to the app. Write-through: writes go to both cache and DB synchronously, keeping them in sync. Both patterns hide cache management from the app code; the cache library handles it.

Question

What is cache-aside?

Answer

Cache-aside (lazy loading): the app checks the cache first; on miss, queries the DB, then writes the result back into the cache. Simple and explicit — the app code stays in control. Most production caches use this pattern. Trade-off: app must manage invalidation manually.

Question

What is cache invalidation?

Answer

Removing or updating cached entries when the underlying data changes. Strategies: TTL-based (auto-expire), event-based (publish DB change → invalidate), version keys (bump a version, old keys ignored). Famously one of the two hard problems in computer science — get it wrong and users see stale data.

Question

What is TTL?

Answer

Time-to-live: how long a cached entry stays valid before automatic expiry. Short TTL = fresh but more cache misses (and load on the DB). Long TTL = better hit rate but more stale data. Tune per use case; many systems combine TTL with explicit invalidation.

Question

Database backup vs replication?

Answer

Backups are point-in-time copies for disaster recovery — restore to last night if something catastrophic happens. Replication is a continuous copy for HA and read scaling. You need BOTH: replication doesn't save you from a bad migration that nukes a table, and backups don't fail over instantly.

Question

What is PITR?

Answer

Point-In-Time Recovery: combining a base backup with the WAL (transaction log) to restore the DB to any moment between the backup and the latest WAL entry. The way to recover from 'a script just deleted production data at 2:43pm' without losing data afterward.

Question

What is a database connection limit?

Answer

The maximum concurrent connections a DB accepts. Each connection consumes significant memory (Postgres ~10MB+). High-traffic apps must front the DB with a pooler (PgBouncer, RDS Proxy) to multiplex thousands of app connections onto a few hundred DB connections.

Question

When should you use NoSQL?

Answer

When you need schema flexibility, massive horizontal scale, simple access patterns (key-value lookups, document queries), or very high write throughput. NOT when you need complex joins, strict ACID across rows, or rich ad-hoc analytics. Use the right tool for the access pattern, not 'because it's modern'.

Question

Cassandra vs MongoDB?

Answer

Cassandra: column-family store, peer-to-peer multi-master, AP-leaning, optimized for huge write throughput across data centers. Mongo: document store, mostly-master with replica sets, richer query language. Cassandra wins on raw scale; Mongo wins on developer ergonomics for typical app workloads.

Question

What is the dual-writes problem?

Answer

Writing the same change to two systems (DB and a message broker, for example) without atomicity. If the first succeeds and the second fails, the systems diverge. Solutions: the outbox pattern (write the message into the DB transaction, ship later) or CDC (capture DB changes and publish them).

Question

What is CDC?

Answer

Change Data Capture: tailing the database's transaction log and emitting events for every change. Tools like Debezium read the WAL/binlog and publish to Kafka. Lets you keep search indexes, caches, and downstream services in sync without dual-writes.

Question

What is the outbox pattern?

Answer

Inside your main DB transaction, write the desired event into an 'outbox' table. A background worker reads the outbox and publishes to your message broker, marking events as sent. Both happen atomically because they share one transaction — no dual-writes problem.

Question

What is snapshot isolation?

Answer

Each transaction sees a consistent snapshot of the data as it existed at the start of the transaction. Writes detect conflicts at commit time (write-write conflicts → one txn aborts). Implemented via MVCC; common in Postgres (REPEATABLE READ behaves like snapshot).

Question

What is a hot partition?

Answer

A shard or partition receiving disproportionate traffic, becoming a bottleneck while others sit idle. Classic cause: shard key is timestamp or sequential, so all new writes hit one shard. The fix is usually a different shard key or sub-sharding the hot key.

Question

What is bulk insert?

Answer

Inserting many rows in a single statement or transaction, rather than one round-trip per row. Orders of magnitude faster: Postgres COPY, MySQL LOAD DATA, JDBC batched executeBatch. Always use bulk inserts for ETL, imports, or initial data seeding.

Question

What is a covering query?

Answer

A query whose results come entirely from an index — no table lookup needed. Add INCLUDE columns to your index for the payload data you frequently SELECT alongside the indexed columns. Huge speed up for hot read paths; cost is a slightly larger index and slower writes.

Practise Databases in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend JavaScript & TypeScript Backend Engineering System Design AI & Agentic AI DevOps & Cloud Security Testing DSA Coding Problems (Python)