🗄️

Database Management Systems MCQ

Test your DBMS knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

What is a database?

B

Correct Answer

An organized collection of structured data stored and accessed electronically

Explanation

A database is a structured collection of data organized for efficient retrieval, modification, and management. A DBMS manages the database, providing abstraction over raw storage.

2

What is a primary key?

B

Correct Answer

A column or set of columns uniquely identifying each row in a table, with no NULL values allowed

Explanation

A primary key ensures row uniqueness. It cannot be NULL and must be unique. A table can have only one primary key (though it may span multiple columns — composite key).

3

What is a foreign key?

B

Correct Answer

A column referencing the primary key of another table, enforcing referential integrity

Explanation

Foreign keys enforce referential integrity: the value must exist in the referenced primary key column. They define relationships between tables (one-to-many, many-to-many via junction tables).

4

What does SQL stand for?

A

Correct Answer

Structured Query Language

Explanation

SQL (Structured Query Language) is the standard language for relational database operations: querying (SELECT), inserting (INSERT), updating (UPDATE), deleting (DELETE), and defining schemas (DDL).

5

What does SELECT * FROM users do?

C

Correct Answer

Retrieves all columns and all rows from the users table

Explanation

SELECT * retrieves all columns. FROM users specifies the table. Adding WHERE, ORDER BY, LIMIT refines the result set. SELECT * is avoided in production due to performance and coupling concerns.

6

What is normalization?

B

Correct Answer

Organizing a database to reduce redundancy and improve data integrity by dividing data into related tables

Explanation

Normalization applies normal forms (1NF, 2NF, 3NF, BCNF) to eliminate data redundancy. It prevents update, insertion, and deletion anomalies.

7

What is the difference between DDL and DML?

B

Correct Answer

DDL (Data Definition Language) defines schema (CREATE, ALTER, DROP); DML (Data Manipulation Language) manipulates data (INSERT, UPDATE, DELETE, SELECT)

Explanation

DDL: CREATE TABLE, ALTER TABLE, DROP TABLE — changes database structure. DML: SELECT, INSERT, UPDATE, DELETE — works with data. DCL (GRANT/REVOKE) controls permissions.

8

What is a JOIN in SQL?

B

Correct Answer

Combining rows from two or more tables based on a related column

Explanation

JOINs combine rows based on matching column values. INNER JOIN returns only matching rows. LEFT JOIN returns all left-table rows plus matching right rows. RIGHT JOIN is the reverse.

9

What is the difference between INNER JOIN and LEFT JOIN?

B

Correct Answer

INNER JOIN returns only rows with matches in both tables; LEFT JOIN returns all rows from the left table and matching rows from the right (NULLs for no match)

Explanation

INNER JOIN: intersection of both tables. LEFT (OUTER) JOIN: all left table rows, with NULLs where no right-table match. Used when you want all records from one table regardless of matches.

10

What is an index in a database?

B

Correct Answer

A data structure that improves query speed by providing fast access paths to rows without scanning the entire table

Explanation

Indexes (B-tree by default in most RDBMS) speed up WHERE, JOIN, and ORDER BY on indexed columns. They consume storage and slow down writes — add them for frequently queried columns.

11

What is ACID in databases?

B

Correct Answer

Atomicity, Consistency, Isolation, Durability — properties guaranteeing reliable transaction processing

Explanation

Atomicity: all-or-nothing. Consistency: valid state before and after. Isolation: concurrent transactions don't interfere. Durability: committed transactions survive failures.

12

What is a transaction?

B

Correct Answer

A sequence of database operations executed as a single logical unit of work that either fully completes or fully rolls back

Explanation

Transactions group operations (e.g., debit one account, credit another). BEGIN/START TRANSACTION...COMMIT persists changes. ROLLBACK undoes all changes if any step fails.

13

What is a stored procedure?

B

Correct Answer

A precompiled set of SQL statements stored in the database and executed as a unit by name

Explanation

Stored procedures are compiled once and stored server-side, reducing network round-trips and allowing code reuse. They can accept parameters and return results.

14

What is a view in SQL?

B

Correct Answer

A named virtual table based on a SELECT query, presenting a subset or transformation of underlying table data

Explanation

Views simplify complex queries, restrict column/row access for security, and provide abstraction. Most views are not materialized (no data stored) — the query runs at access time.

15

What does GROUP BY do in SQL?

B

Correct Answer

Groups rows with the same values in specified columns, used with aggregate functions like COUNT, SUM, AVG

Explanation

GROUP BY creates groups of rows with identical values. Aggregate functions compute per-group. SELECT dept, COUNT(*) FROM employees GROUP BY dept counts employees per department.

16

What is the difference between WHERE and HAVING?

A

Correct Answer

WHERE filters rows before grouping; HAVING filters groups after grouping

Explanation

WHERE filters rows before GROUP BY aggregation. HAVING filters groups after aggregation. You can't use aggregate functions in WHERE: use HAVING COUNT(*) > 5 not WHERE COUNT(*) > 5.

17

What is the purpose of ORDER BY?

B

Correct Answer

Sorting query results in ascending (ASC) or descending (DESC) order by specified columns

Explanation

ORDER BY col ASC (default) or DESC. Multiple columns: ORDER BY last_name, first_name. Without ORDER BY, result order is undefined in SQL.

18

What is a NULL value in SQL?

B

Correct Answer

The absence of a value — different from empty string or zero

Explanation

NULL represents missing or unknown data. NULL arithmetic returns NULL. Use IS NULL / IS NOT NULL (not = NULL). Three-valued logic: TRUE, FALSE, UNKNOWN (NULL comparisons return UNKNOWN).

19

What is the difference between CHAR and VARCHAR?

B

Correct Answer

CHAR stores fixed-length strings (padded with spaces); VARCHAR stores variable-length strings up to a maximum

Explanation

CHAR(10) always stores 10 bytes (padded). VARCHAR(100) stores up to 100 bytes, using only what's needed plus 1-2 bytes for length. CHAR is slightly faster for fixed-length data like codes.

20

What is a database schema?

B

Correct Answer

The logical structure defining tables, columns, data types, constraints, and relationships

Explanation

A schema is the blueprint of a database: table definitions, column types, primary/foreign keys, indexes, and constraints. It is separate from the data itself.

21

What is denormalization?

B

Correct Answer

Intentionally introducing redundancy to improve read performance at the cost of data integrity and write overhead

Explanation

Denormalization (used in OLAP, data warehouses, and high-read systems) adds redundant columns or pre-joined tables to avoid expensive JOINs, trading storage/write overhead for faster reads.

22

What is a composite key?

B

Correct Answer

A primary key made up of two or more columns together uniquely identifying each row

Explanation

A composite (compound) key uses multiple columns to form a unique identifier. Example: in an enrollment table, (student_id, course_id) together form the primary key.

23

What does DISTINCT do in SQL?

B

Correct Answer

Returns only unique values, removing duplicate rows from the result set

Explanation

SELECT DISTINCT city FROM customers returns each city name only once. Without DISTINCT, duplicates appear for each row with that city.

24

What is a trigger in databases?

B

Correct Answer

A database object that automatically executes a specified action in response to DML events (INSERT, UPDATE, DELETE) on a table

Explanation

Triggers fire automatically BEFORE or AFTER INSERT/UPDATE/DELETE events. Used for auditing, enforcing complex constraints, or maintaining derived data.

25

What is the difference between TRUNCATE and DELETE?

B

Correct Answer

TRUNCATE removes all rows quickly without logging individual rows and cannot be rolled back easily; DELETE removes rows with WHERE clause support and is fully logged

Explanation

TRUNCATE is DDL (not DML), resets the table to empty quickly (minimal logging), and cannot fire row-level triggers. DELETE is DML, supports WHERE, fires triggers, and is fully transactional.

26

What is a relational database?

B

Correct Answer

A database organizing data into tables (relations) with rows and columns, using SQL and enforcing relationships via keys

Explanation

Relational databases (MySQL, PostgreSQL, Oracle, SQL Server) are based on Codd's relational model. Data is stored in tables with defined schemas and relationships.

27

What is the difference between a clustered and non-clustered index?

B

Correct Answer

A clustered index physically orders table rows by the index key; a non-clustered index is a separate structure with pointers to rows

Explanation

A table can have only one clustered index (determines physical row order — typically the primary key in MySQL InnoDB). Non-clustered indexes are separate B-trees with row pointers.

28

What is a subquery?

B

Correct Answer

A query nested inside another SQL query, used to provide data for the outer query

Explanation

Subqueries can appear in SELECT, FROM, WHERE, and HAVING clauses. Example: SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees).

29

What is database replication?

B

Correct Answer

Copying and maintaining database changes across multiple servers to improve availability and read scalability

Explanation

Replication synchronizes data across multiple database servers. Master-slave (primary-replica) replication sends writes to primary; replicas handle reads, improving scalability and providing failover.

30

What is the LIMIT clause in SQL?

B

Correct Answer

Restricting the number of rows returned by a query

Explanation

SELECT * FROM products ORDER BY price DESC LIMIT 10 returns the 10 most expensive products. MySQL/PostgreSQL use LIMIT; SQL Server uses TOP; Oracle uses ROWNUM or FETCH FIRST.

31

What is a database cursor?

B

Correct Answer

A database object enabling row-by-row processing of query results

Explanation

Cursors iterate over result sets one row at a time in stored procedures. Generally avoided for set-based operations (SQL thinks in sets), but useful for row-by-row processing when necessary.

32

What is the difference between a relation and a table?

B

Correct Answer

A relation is the mathematical set-based concept (no duplicates, no order); a table is a SQL implementation (allows duplicates, ordered storage)

Explanation

In relational theory, a relation is a set of tuples (no duplicates, no order). SQL tables may have duplicate rows (multisets) and ordered result sets, relaxing strict mathematical relations.

33

What is a database transaction log?

B

Correct Answer

A record of all database changes (before and after images) used for recovery after failures

Explanation

The transaction log (write-ahead log / WAL) records all changes before applying them to data files. On crash recovery, the DBMS replays committed transactions and undoes uncommitted ones using this log.

34

What is a self-join?

B

Correct Answer

A join where a table is joined to itself, typically to compare rows within the same table or find hierarchical relationships

Explanation

Self-join: SELECT e.name AS employee, m.name AS manager FROM employees e JOIN employees m ON e.manager_id = m.id — finds each employee's manager from the same employees table.

35

What is an ERD (Entity-Relationship Diagram)?

B

Correct Answer

A visual representation of entities, their attributes, and the relationships between them in a database design

Explanation

ERDs (Chen notation, Crow's foot notation) help design databases before implementation. Entities become tables, attributes become columns, and relationships define foreign keys.

36

What are aggregate functions in SQL?

B

Correct Answer

Functions that perform calculations on sets of values and return a single value: COUNT, SUM, AVG, MAX, MIN

Explanation

COUNT(*) counts rows. SUM(salary) totals salary. AVG(price) averages price. MAX/MIN find extremes. Used with GROUP BY to compute per-group statistics.

37

What is OLTP vs OLAP?

B

Correct Answer

OLTP (Online Transaction Processing) handles frequent short transactions; OLAP (Online Analytical Processing) handles complex analytical queries on large datasets

Explanation

OLTP: order processing, banking — high concurrency, simple queries, normalized schema. OLAP: data warehousing, BI — complex aggregations, denormalized star/snowflake schema, fewer concurrent users.

38

What is a unique constraint?

B

Correct Answer

A constraint ensuring all values in a column are distinct (allows one NULL unless combined with NOT NULL)

Explanation

UNIQUE constraint prevents duplicate non-NULL values. Unlike PRIMARY KEY, multiple UNIQUE columns are allowed per table, and they can accept NULL values (behavior varies by DBMS).

39

What is the BETWEEN operator in SQL?

B

Correct Answer

Selects values within an inclusive range: WHERE price BETWEEN 10 AND 50

Explanation

WHERE age BETWEEN 18 AND 65 is equivalent to WHERE age >= 18 AND age <= 65. Works with numbers, dates, and strings. BETWEEN is inclusive on both ends.

40

What is a NoSQL database?

B

Correct Answer

A category of databases using non-relational storage models (document, key-value, column-family, graph) designed for scale and flexibility

Explanation

NoSQL databases (MongoDB, Redis, Cassandra, Neo4j) sacrifice some ACID guarantees for horizontal scalability and flexible schemas. Best for unstructured data, high write throughput, or specific access patterns.

1

What is the first normal form (1NF)?

B

Correct Answer

Each column must contain atomic (indivisible) values; no repeating groups or arrays in columns

Explanation

1NF: atomic values (no lists/arrays in cells), unique column names, order of rows doesn't matter. If a column holds comma-separated values, it violates 1NF.

2

What is the third normal form (3NF)?

A

Correct Answer

All columns must depend on the primary key, not on each other (no transitive dependencies)

Explanation

3NF: all non-key columns must be directly dependent on the primary key (not on other non-key columns). Example: if ZIP→City, store ZIP and City in a separate table.

3

What is a transaction isolation level?

B

Correct Answer

A setting controlling how transaction changes are visible to other concurrent transactions, balancing consistency vs. concurrency

Explanation

SQL isolation levels: READ UNCOMMITTED (dirty reads), READ COMMITTED (default, no dirty reads), REPEATABLE READ (no non-repeatable reads), SERIALIZABLE (no phantom reads). Higher isolation = lower concurrency.

4

What is a dirty read in database transactions?

B

Correct Answer

Reading uncommitted data from another transaction that may later be rolled back

Explanation

A dirty read occurs at READ UNCOMMITTED isolation: Transaction A reads data written by Transaction B before B commits. If B rolls back, A has read invalid data.

5

What is the difference between optimistic and pessimistic locking?

B

Correct Answer

Pessimistic: lock before reading/writing (assumes conflicts); Optimistic: check at commit time for conflicts (assumes no conflicts), better for low-contention scenarios

Explanation

Pessimistic: acquire row locks before modifying. Optimistic: read with a version number, check at commit that no other transaction changed the data. Optimistic has higher throughput but may require retries.

6

What is a B-tree index?

B

Correct Answer

A self-balancing tree data structure used for indexing, providing O(log n) search, insert, and delete for range queries and equality lookups

Explanation

B-tree (balanced tree) indexes support equality (=), range (<, >, BETWEEN), ORDER BY, and GROUP BY operations efficiently. The tree height is O(log n), so queries touch few disk pages.

7

What is a hash index?

B

Correct Answer

An index using a hash function to map keys to bucket positions, providing O(1) equality lookups but not supporting range queries

Explanation

Hash indexes provide O(1) equality lookups but cannot support range queries, ORDER BY, or partial key lookups. In PostgreSQL they're useful for equality-only workloads; MySQL InnoDB doesn't support them.

8

What is sharding in databases?

B

Correct Answer

Horizontally partitioning data across multiple database servers, each holding a subset of rows (shard), for scalability

Explanation

Sharding scales writes horizontally. Shard key determines which shard holds a row (e.g., user_id % N). Challenges: cross-shard queries, rebalancing, and maintaining ACID across shards.

9

What is database partitioning?

B

Correct Answer

Dividing a large table into smaller segments (partitions) stored separately, improving query performance via partition pruning

Explanation

Partitioning (range, hash, list, composite) splits table data physically. Queries on the partition key skip non-relevant partitions (partition pruning), dramatically reducing I/O for large tables.

10

What is the difference between correlated and uncorrelated subqueries?

B

Correct Answer

A correlated subquery references the outer query and executes once per outer row; an uncorrelated subquery executes once independently

Explanation

Uncorrelated: SELECT * FROM t WHERE salary > (SELECT AVG(salary) FROM t) — inner query runs once. Correlated: per-outer-row execution — often slow, replaceable with JOINs.

11

What is the CAP theorem's relevance to distributed databases?

B

Correct Answer

Distributed databases must choose between Consistency and Availability when network partitions occur; no system can guarantee all three simultaneously

Explanation

Cassandra/DynamoDB choose Availability+Partition (AP). HBase/Zookeeper choose Consistency+Partition (CP). No practical distributed database can be fully consistent and available during network partitions.

12

What is a materialized view?

B

Correct Answer

A view whose query result is physically stored and refreshed periodically, trading storage for faster read performance

Explanation

Materialized views store query results on disk. Unlike regular views (recomputed each access), they are precomputed. Used in data warehouses for aggregation queries. Require refresh strategies (on demand, periodic, on-change).

13

What is query optimization?

B

Correct Answer

The database engine's process of selecting the most efficient execution plan for a query using statistics, join algorithms, and index choices

Explanation

The query optimizer (cost-based optimizer) evaluates multiple execution plans, estimating cost using statistics (row counts, cardinality, data distribution) and choosing the cheapest plan.

14

What is the purpose of database statistics?

B

Correct Answer

Metadata about data distribution (row counts, value frequencies, histograms) used by the query optimizer to choose efficient execution plans

Explanation

Statistics (e.g., pg_statistics in PostgreSQL) inform the optimizer about actual data distribution. Stale statistics cause bad query plans. ANALYZE (PostgreSQL) or UPDATE STATISTICS (SQL Server) refresh them.

15

What is a deadlock in a database context?

B

Correct Answer

Two or more transactions each holding locks needed by the other, causing mutual blocking and requiring the DBMS to abort one

Explanation

Database deadlocks: TXN A holds lock on row 1, wants row 2; TXN B holds lock on row 2, wants row 1. DBMS detects the cycle and kills one transaction (the "victim").

16

What is MVCC (Multi-Version Concurrency Control)?

B

Correct Answer

A concurrency control method maintaining multiple versions of data so readers don't block writers and writers don't block readers

Explanation

MVCC (PostgreSQL, Oracle, MySQL InnoDB) stores old row versions for concurrent reads. Readers see a consistent snapshot at transaction start without blocking writers. PostgreSQL uses tuple versioning; MySQL uses undo logs.

17

What is a cursor in database programming?

B

Correct Answer

A database object that allows row-by-row iteration through a result set in stored procedures or application code

Explanation

Cursors enable procedural processing of query results. They are generally inefficient (row-by-row vs. set operations). Server-side cursors (PL/pgSQL, T-SQL) run in DB; client-side cursors fetch to client memory.

18

What is database connection pooling?

B

Correct Answer

Maintaining a pool of pre-established database connections that applications reuse, avoiding connection creation overhead

Explanation

Connection pools (PgBouncer, HikariCP, c3p0) reuse connections. Each new connection takes ~50ms and resources. Pools maintain N ready connections for instant checkout, improving throughput dramatically.

19

What is a covering index?

B

Correct Answer

An index containing all columns needed by a query, allowing the query to be satisfied entirely from the index without touching the table data

Explanation

A covering index includes all SELECT, WHERE, and JOIN columns for a query. The query can be answered from the index alone (index-only scan), avoiding expensive heap fetches.

20

What is the difference between SQL and NoSQL databases for scalability?

B

Correct Answer

SQL databases scale vertically (bigger server) more naturally; NoSQL databases are designed for horizontal scaling across many commodity nodes

Explanation

SQL ACID constraints make distributed horizontal scaling hard (distributed transactions are expensive). NoSQL (Cassandra, DynamoDB) sacrifices strong consistency for linear horizontal write scaling.

21

What is a foreign key constraint and cascading?

B

Correct Answer

Referential integrity enforcement with cascade options: ON DELETE CASCADE automatically deletes child rows when parent is deleted

Explanation

ON DELETE CASCADE: deleting parent deletes all children. ON DELETE SET NULL: sets FK to NULL. ON DELETE RESTRICT (default): prevents parent delete if children exist. Cascading prevents orphaned records.

22

What is data warehousing?

B

Correct Answer

A system for collecting, storing, and analyzing large volumes of historical data from multiple sources for business intelligence and reporting

Explanation

Data warehouses (Snowflake, Redshift, BigQuery) are optimized for OLAP queries with star/snowflake schemas, columnar storage, and MPP (massively parallel processing) for fast aggregations.

23

What is the difference between star schema and snowflake schema?

B

Correct Answer

Star schema has denormalized dimensions (fewer JOINs); snowflake normalizes dimensions into sub-dimensions (more JOINs, less storage)

Explanation

Star schema: fact table + denormalized dimension tables. Simple JOINs, faster queries, more storage. Snowflake: normalized dimensions into hierarchies. More JOINs but better data integrity and less storage.

24

What is a window function in SQL?

B

Correct Answer

A function computing values across a set of rows related to the current row without collapsing them into one group, using OVER() clause

Explanation

Window functions (ROW_NUMBER(), RANK(), LAG(), SUM() OVER()) perform calculations across related rows while returning individual rows. Essential for running totals, rankings, and lag/lead analysis.

25

What is the difference between UNION and UNION ALL?

B

Correct Answer

UNION removes duplicates from combined results; UNION ALL keeps all rows including duplicates and is faster

Explanation

UNION performs a DISTINCT sort to remove duplicates (slower). UNION ALL appends all rows from both queries without duplicate removal (faster). Use UNION ALL when duplicates are acceptable or not possible.

26

What is a database trigger and when should it be avoided?

B

Correct Answer

Triggers automate actions but should be avoided when they create hidden logic, complex debugging scenarios, or performance issues — prefer application-layer constraints

Explanation

Triggers make debugging hard (invisible logic), can cause cascading effects, and impact performance. Use for audit logging, but prefer application-layer logic for business rules to maintain transparency.

27

What is columnar storage and why is it used in analytical databases?

B

Correct Answer

Storing data column-by-column rather than row-by-row, enabling efficient compression and I/O for analytical queries that aggregate specific columns

Explanation

Columnar storage (Parquet, ORC, Redshift, BigQuery) reads only queried columns (not entire rows), enables high compression ratios of similar data, and uses SIMD operations for vectorized processing.

28

What is the second normal form (2NF)?

A

Correct Answer

A table is in 1NF and every non-key column is fully functionally dependent on the entire primary key, eliminating partial dependencies

Explanation

2NF removes partial dependencies that occur with composite keys: a non-key column depending on only part of the composite key must be moved to its own table. This applies only when the primary key has multiple columns.

29

What does the EXPLAIN command show in most relational databases?

C

Correct Answer

The query optimizer's chosen execution plan, including operations like scans, joins, and the order in which they run

Explanation

EXPLAIN reveals how the database intends to execute a query: which indexes it uses, the join order, and the access methods (sequential scan vs. index scan). It is the primary tool for diagnosing slow queries.

30

What is a non-repeatable read?

D

Correct Answer

When a transaction reads the same row twice and gets different values because another committed transaction modified it in between

Explanation

Non-repeatable reads occur at READ COMMITTED isolation: re-querying the same row mid-transaction can return updated values from a transaction that committed in between. REPEATABLE READ isolation prevents this by maintaining a consistent snapshot.

31

What is a phantom read?

A

Correct Answer

When a transaction re-runs a range query and finds new rows that another committed transaction inserted, which weren't present the first time

Explanation

Phantom reads happen when a range query (e.g., WHERE age > 30) returns a different set of rows on re-execution because rows matching the predicate were inserted or deleted by other committed transactions. SERIALIZABLE isolation prevents this.

32

What is the purpose of the EXISTS operator in SQL?

D

Correct Answer

To test whether a subquery returns at least one row, often more efficient than IN for correlated subqueries since it can stop at the first match

Explanation

EXISTS returns TRUE as soon as the subquery produces one matching row, short-circuiting further evaluation. This often makes it faster than IN for large correlated subqueries, especially when the optimizer can use semi-join strategies.

33

What is referential integrity?

C

Correct Answer

A property ensuring that foreign key values always correspond to existing primary key values in the referenced table, preventing orphaned records

Explanation

Referential integrity is enforced through foreign key constraints: a row cannot reference a non-existent parent row, and the DBMS rejects operations (or cascades them) that would break this relationship.

34

What is an anti-join in SQL?

C

Correct Answer

A query pattern (typically using NOT EXISTS or LEFT JOIN ... WHERE right.col IS NULL) that returns rows from one table that have no matching rows in another table

Explanation

Anti-joins find "rows in A without a match in B" — for example, customers who have never placed an order. NOT EXISTS and LEFT JOIN/IS NULL are common implementations, and the optimizer can rewrite NOT IN into an efficient anti-join plan.

35

What is the purpose of the EXPLAIN ANALYZE command compared to plain EXPLAIN?

B

Correct Answer

EXPLAIN ANALYZE actually executes the query and reports real row counts and timings alongside the planner's estimates, helping spot inaccurate statistics

Explanation

Plain EXPLAIN shows only estimated costs and row counts from the optimizer. EXPLAIN ANALYZE runs the query and adds actual elapsed time and row counts, making it possible to see where estimates diverge sharply from reality, often the root cause of a bad plan.

36

What is a surrogate key?

C

Correct Answer

An artificial, system-generated identifier (such as an auto-incrementing integer or UUID) used as a primary key instead of a natural business attribute

Explanation

Surrogate keys (e.g., auto-increment IDs, UUIDs) have no business meaning and remain stable even if real-world attributes change. This avoids problems that arise when natural keys (like email or SSN) are later edited or reused.

37

What is the purpose of the GRANT and REVOKE statements in SQL?

D

Correct Answer

To assign and remove user privileges on database objects, forming the Data Control Language (DCL) portion of SQL

Explanation

GRANT SELECT ON table TO user and REVOKE SELECT ON table FROM user manage access permissions at the object level. Together with DENY in some systems, they form DCL, the part of SQL responsible for security and authorization.

38

What is query result caching and what risk does it introduce?

C

Correct Answer

Storing the output of a query so repeated identical requests skip re-execution, with the risk of returning stale results if underlying data changes before the cache is invalidated

Explanation

Caching layers (application-level caches, query caches) avoid redundant computation for repeated reads, greatly reducing load. The trade-off is staleness: if the cache isn't invalidated when data changes, clients may see outdated results.

39

What is the difference between a natural join and an inner join with an explicit ON clause?

D

Correct Answer

A natural join automatically matches columns with the same name in both tables, which can produce unexpected results if unrelated columns happen to share a name; an explicit ON clause makes the join condition clear and predictable

Explanation

NATURAL JOIN implicitly joins on all identically named columns, which is convenient but fragile — adding a new column with a matching name in either table silently changes the join semantics. Explicit ON clauses are preferred because they document intent and avoid such surprises.

40

What is the purpose of the COALESCE function in SQL?

C

Correct Answer

To return the first non-NULL value from a list of expressions, commonly used to substitute default values for NULLs

Explanation

COALESCE(phone, mobile, 'N/A') evaluates its arguments left to right and returns the first one that is not NULL. It is a portable, standard-SQL alternative to vendor-specific functions like ISNULL or NVL for handling missing data gracefully.

1

What is the difference between 2PL (Two-Phase Locking) and MVCC?

B

Correct Answer

2PL acquires all locks before releasing any (expanding then shrinking phases), blocking readers; MVCC uses versions to allow readers and writers to proceed concurrently

Explanation

Strict 2PL: all locks released at commit, preventing cascading aborts. 2PL blocks readers with writers. MVCC lets readers see a consistent snapshot without blocking writers, improving concurrency at the cost of storage for old versions.

2

What is the Aries recovery algorithm?

B

Correct Answer

A WAL-based recovery algorithm using analysis, redo (all operations from last checkpoint), and undo (uncommitted transactions) phases to ensure ACID recovery after crashes

Explanation

ARIES (Algorithms for Recovery and Isolation Exploiting Semantics): uses WAL, steal/no-force buffer policy. Three phases: Analysis (determine dirty pages/active TXNs), Redo (redo from last checkpoint), Undo (roll back uncommitted TXNs).

3

What is lock escalation in databases?

B

Correct Answer

The database automatically converting many fine-grained locks (row locks) to coarser-grained locks (page or table locks) to reduce lock overhead when too many locks are held

Explanation

Lock escalation trades fine-grained concurrency for lower memory overhead. SQL Server escalates to table locks after ~5,000 row locks. Can cause unexpected blocking; disable per-table when problematic.

4

What is the difference between read committed and repeatable read isolation levels?

B

Correct Answer

Read committed sees only committed data but allows non-repeatable reads (same query returns different results); repeatable read prevents this but allows phantom reads

Explanation

Read committed: re-reading a row may return updated data from committed TXNs (non-repeatable read). Repeatable read: row values don't change during a TXN, but new rows (phantoms) may appear. Serializable prevents phantoms too.

5

What is a query execution plan and how do you analyze it?

B

Correct Answer

A tree of physical operations (table scans, index seeks, joins, sorts) the optimizer chose to execute a query — analyzed with EXPLAIN/EXPLAIN ANALYZE to find bottlenecks

Explanation

EXPLAIN (PostgreSQL) or EXPLAIN PLAN (Oracle) shows the execution plan. EXPLAIN ANALYZE actually runs and shows real vs. estimated row counts. Look for sequential scans on large tables, nested loops over large sets, and incorrect cardinality estimates.

6

What is database connection pooling vs. connection multiplexing?

B

Correct Answer

Connection pooling reuses connections per application process; multiplexing (PgBouncer transaction mode) shares one server connection across many client transactions, reducing server-side connection count

Explanation

PgBouncer in transaction mode multiplexes: many clients share few server connections (one per concurrent transaction, not per client). This allows 10,000 app connections with only 100 PostgreSQL connections.

7

What is the difference between synchronous and asynchronous replication?

B

Correct Answer

Synchronous: commit waits for replica acknowledgment (no data loss, higher latency); Asynchronous: commit returns immediately (potential data loss, lower latency)

Explanation

Synchronous replication (sync standby in PostgreSQL) waits for replica to write WAL before returning. Zero RPO but adds replica latency to every write. Async replication may lose committed data if primary crashes before replica catches up.

8

What is a LSM-tree and which databases use it?

B

Correct Answer

A Log-Structured Merge-tree that buffers writes in memory and periodically merges sorted files, enabling high write throughput at the cost of read amplification

Explanation

LSM-trees (RocksDB, Cassandra, LevelDB, HBase) convert random writes to sequential I/O by appending to memtables flushed as SSTables. Compaction merges SSTables. High write throughput; reads require checking multiple levels.

9

What is write amplification in database storage engines?

B

Correct Answer

The ratio of data written to storage vs. data actually written by the application — caused by compaction, journaling, and copy-on-write mechanisms

Explanation

A single 4KB write may cause 20KB of actual storage writes (WAL write, B-tree page write, checkpoint). LSM-tree compaction amplifies writes. High write amplification wears SSDs faster and reduces throughput.

10

What is the Saga pattern in distributed transactions?

B

Correct Answer

A pattern breaking a distributed transaction into a sequence of local transactions with compensating transactions for rollback, avoiding 2PC across services

Explanation

The Saga pattern (choreography or orchestration) handles distributed transactions without 2PC. Each step has a compensating transaction for undo. Used in microservices where ACID across services is impractical.

11

What is the difference between PostgreSQL's MVCC and MySQL InnoDB's MVCC?

B

Correct Answer

PostgreSQL keeps old versions in the heap (requires VACUUM); InnoDB stores old versions in a separate undo log, with automatic cleanup via purge threads

Explanation

PostgreSQL: dead tuples stay in heap pages until VACUUM reclaims them (table bloat risk). InnoDB: undo log stores versions, purged by background threads. Different approaches to old version management.

12

What is write-ahead logging (WAL) and why is it fundamental to database recovery?

B

Correct Answer

The principle that log records describing changes must be written to durable storage before the data pages they describe, enabling crash recovery without losing committed data

Explanation

WAL ensures durability and enables recovery. Before writing a dirty page, its log record is flushed (log-ahead). On recovery: redo committed TXNs from log, undo uncommitted ones. Enables ARIES recovery protocol.

13

What is temporal data management in databases?

B

Correct Answer

Storing and querying data with time dimensions: transaction time (when stored) and valid time (real-world validity), enabled by SQL:2011 temporal tables

Explanation

Temporal databases track "valid time" (when a fact is true in the real world) and "transaction time" (when data was stored). SQL:2011 adds PERIOD, VERSIONING, and temporal JOINs for bitemporal queries.

14

What is the difference between row-level security and view-based security?

B

Correct Answer

Row-level security (RLS) enforces access control policies at the database engine level per row; views restrict visible rows but can be bypassed if users have direct table access

Explanation

PostgreSQL RLS: CREATE POLICY defines row-visibility predicates applied automatically to all queries on the table. Users cannot bypass RLS even with direct table access. Views require denying direct table access separately.

15

What is the Google Spanner database and its significance?

B

Correct Answer

A globally distributed relational database achieving external consistency using TrueTime (atomic clocks + GPS) to assign commit timestamps, enabling ACID across data centers

Explanation

Spanner (Corbett et al., 2012) provides global SQL with ACID transactions using Paxos consensus and TrueTime. TrueTime bounds clock uncertainty, enabling globally consistent reads and serializable distributed transactions.

16

What is HTAP (Hybrid Transactional/Analytical Processing)?

B

Correct Answer

A database architecture supporting both OLTP (transactional) and OLAP (analytical) workloads on the same data simultaneously without ETL delays

Explanation

HTAP systems (TiDB, SingleStore, CockroachDB, SQL Server with columnstore) eliminate the ETL pipeline to the data warehouse, enabling real-time analytics on live transactional data.

17

In the context of distributed transactions, what problem does the Two-Phase Commit (2PC) protocol solve, and what is its main weakness?

C

Correct Answer

It coordinates a commit decision across multiple nodes so all participants either commit or abort together, but a coordinator failure after the prepare phase can leave participants blocked holding locks indefinitely

Explanation

2PC has a prepare phase (participants vote to commit or abort) and a commit phase (coordinator broadcasts the final decision). If the coordinator crashes after participants vote "yes" but before sending the decision, those participants remain blocked holding locks — the protocol's well-known "blocking problem," which Paxos/Raft-based commit protocols aim to avoid.

18

How does cost-based query optimization decide between a nested loop join and a hash join?

D

Correct Answer

It estimates the cost of each strategy using table sizes, available indexes, and selectivity statistics — favoring nested loop joins when one side is small and indexed, and hash joins when both sides are large and unsorted with no useful index

Explanation

The cost-based optimizer compares estimated I/O and CPU costs for each join strategy given current statistics. Nested loop joins excel when the outer side is small and the inner side has a usable index; hash joins are typically chosen for large, unindexed equi-joins because building an in-memory hash table avoids repeated scans.

19

What is the "thundering herd" problem in the context of database connection and cache management, and how is it typically mitigated?

C

Correct Answer

It happens when a popular cached value expires and many requests simultaneously hit the database to recompute it, overwhelming it — mitigated via request coalescing, regeneration locks, or staggered expiry times

Explanation

When a hot cache entry expires, every waiting request can fall through to the database at once, causing a load spike. Common mitigations include having only one request regenerate the value while others wait (request coalescing/locking), serving slightly stale data while refreshing, and jittering expiration times so entries don't all expire together.

20

What is "snapshot isolation" and how can it still permit write skew anomalies?

D

Correct Answer

Snapshot isolation gives each transaction a consistent view of the database as of its start time, but two concurrent transactions can read the same data, each act on what they saw, and together violate an invariant neither broke alone

Explanation

Under snapshot isolation (used by PostgreSQL's REPEATABLE READ and Oracle's SERIALIZABLE), each transaction sees a consistent snapshot, so it never observes the other's uncommitted writes. However, two transactions can both read the same snapshot, each decide an action is safe based on it, and then commit writes that collectively break an invariant — the classic example being two on-call doctors each independently giving up their shift because the snapshot showed another doctor still on call.