Skip to main content
InterviewHubPRO
HomeTracksSection 14: SQL & Relational Databases (50 Qs)
Section 14 of 6450 Questions (1 Per Page)

Relational Database Engineering & Advanced SQL Architecture Master Interview Bank

ACID transaction isolation levels, B-Tree vs LSM-Tree index structures, EXPLAIN ANALYZE query plan reading, query optimization, and normalization.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Basic & Foundational Concepts (Junior / Entry-Level)

10 Questions
1
Most AskedJuniorCode#Databases & SQL

What are the four sub-languages of SQL (DDL, DML, DCL, TCL)?

SQL commands are categorized into 4 operational sub-languages: DDL (Data Definition Language): Defines and modifies database schema structure: CREATE, ALTER, DROP, TRUNCATE, RENAME • DML (Data Manipulation Language): Modifies and queries data records: SELECT, INSERT, UPDATE, DELETE.

2
Junior#sql-databases#Basic

What is the difference between `DELETE`, `TRUNCATE`, and `DROP`?

DELETE (DML): Removes rows matching a WHERE condition one by one • TRUNCATE (DDL): Deallocates entire physical data pages to empty the table • DROP (DDL): Completely deletes both the data and the table structure/schema definition from the database catalog.

3
Junior#sql-databases#Basic

What are Primary Keys, Foreign Keys, and Unique Constraints?

Primary Key: A column (or set of columns) that uniquely identifies each row in a table • Unique Key: Enforces uniqueness across values in a column • Foreign Key: A column that references the Primary Key of another table, enforcing referential integrity.

4
JuniorCode#Databases & SQL

What are the different types of SQL Joins (INNER, LEFT, RIGHT, FULL, CROSS)?

INNER JOIN: Returns only rows where there is a match in both tables • LEFT (OUTER) JOIN: Returns all rows from the left table, plus matched rows from the right table (unmatched right columns return NULL) • RIGHT (OUTER) JOIN: Returns all rows from the right table, plus matched rows from the left table.

5
Junior#sql-databases#Basic

What is the difference between `WHERE` and `HAVING` clauses?

WHERE: Filters individual rows before any aggregation (GROUP BY) is calculated • HAVING: Filters grouped summary rows after aggregation has occurred.

6
Most AskedJunior#Databases & SQL

What are the common SQL Aggregate Functions?

Aggregate functions perform a calculation on a set of values and return a single scalar value: COUNT(*): Counts total rows (including NULLs) • COUNT(column): Counts non-null rows in that column • SUM(column): Returns the total mathematical sum • AVG(column): Returns the arithmetic mean.

7
Junior#Databases & SQL

What is Database Normalization and why is it used?

Normalization is the process of organizing database schema to eliminate data redundancy and avoid insertion, update, and deletion anomalies: Prevents storing a customer's address in 50 separate order rows; if the customer moves, you only update a single row in the Customers table.

8
Junior#Forms

What are First, Second, and Third Normal Forms (1NF, 2NF, 3NF)?

1NF (First Normal Form) • Each column contains atomic (indivisible) values (no comma-separated lists!) • Each row has a unique identifier (Primary Key) • 2NF (Second Normal Form).

9
Most AskedJunior#Forms

What is Boyce-Codd Normal Form (BCNF)?

BCNF is a stricter version of 3NF: A table is in BCNF if and only if for every functional dependency X \rightarrow Y, X must be a Superkey (candidate key) • Resolves rare anomalies where a table has multiple overlapping composite candidate keys.

10
Most AskedJunior#Databases & SQL

When should you deliberately Denormalize a database?

Strict 3NF requires joining 6 to 10 tables to assemble a complete user profile or invoice, causing heavy CPU and memory join overhead: Denormalization: Intentionally duplicating data into tables (e.g. storing customer_name directly in orders) • Speeds up read-heavy queries by eliminating expensive JOIN operations.

Part 2: Core Architecture & Implementation (Mid-Level)

10 Questions
11
Most AskedSenior#System Design#Databases & SQL

What are the ACID Properties in relational databases?

The 4 foundational guarantees of transactional databases: Atomicity: "All or nothing" • Consistency: A transaction transitions the database from one valid state to another, upholding all constraints, cascades, and schema rules.

12
SeniorCode#System Design#Databases & SQL

What are the 4 ANSI SQL Transaction Isolation Levels and their read phenomena?

Isolation levels define how transactions interact concurrently: Dirty Read: Reading uncommitted changes made by another concurrent transaction (which might subsequently roll back!) • Non-Repeatable Read: Re-reading a row within the same transaction returns different column values because another transaction modified and.

13
SeniorCode#System Design

What are Window Functions and how do they differ from `GROUP BY`?

GROUP BY: Collapses multiple rows into a single summary row • Window Functions (OVER (PARTITION BY .

14
Most AskedSenior#System Design

What is the difference between `ROW_NUMBER()`, `RANK()`, and `DENSE_RANK()`?

When ranking rows with tied values (e.g. two employees with salary $100,000): ROWNUMBER(): Assigns strictly consecutive unique numbers regardless of ties (1, 2, 3, 4) • RANK(): Assigns the same rank to ties, and skips subsequent ranks to reflect the gap (1, 2, 2, 4).

15
SeniorCode#System Design

What are `LEAD()` and `LAG()` window functions used for?

Allows accessing data from preceding or succeeding rows without self-joins: LAG(col, N): Accesses value from N rows before the current row (e.g. comparing today's revenue against yesterday's revenue).

16
Senior#System Design

What is the difference between Correlated and Non-Correlated Subqueries?

Non-Correlated Subquery: Independent of the outer query • Correlated Subquery: References columns from the outer query.

17
Senior#System Design

What is the difference between `EXISTS` and `IN`?

IN: Evaluates all subquery results, builds a candidate set, and checks if the outer value exists in that set • EXISTS: Returns a boolean true as soon as the first matching row is found (short-circuits immediately).

18
Most AskedSeniorCode#System Design#Databases & SQL

How does a B-Tree (and B+ Tree) Index work internally?

Relational databases store table indexes using self-balancing search trees (primarily B+ Trees): Root and Internal Branch Nodes: Store routing keys and child page pointers to direct traversals • Leaf Nodes: Hold the actual keys in sorted sequential order, connected horizontally via doubly linked lists.

19
Most AskedSenior#System Design

What is a Composite Index and the Leftmost Prefix Rule?

An index defined on multiple columns (e.g. INDEX (country, city, postalcode)): The data is sorted by country first, then within each country by city, then by postalcode • Leftmost Prefix Rule: The query optimizer can only use the index if the query filters on the leftmost columns in order.

20
SeniorCode#System Design#Databases & SQL

What is SQL Injection and how do Parameterized Queries (Prepared Statements) prevent it?

SQL injection occurs when untrusted user input is concatenated directly into a SQL query string (e.g. ' OR '1'='1): Parameterized Queries: Separates query SQL code from incoming data parameters.

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

30 Questions
21
Most AskedSenior#sql-databases#Advanced Internals

What is the difference between Clustered and Non-Clustered Indexes?

Clustered Index: Determines the physical, on-disk storage order of rows • Non-Clustered Index: A separate structure from data rows.

22
Senior#sql-databases#Advanced Internals

What are the three primary physical Join Algorithms (Nested Loop, Hash Join, Merge Join)?

Nested Loop Join: Outer loop iterates through Table A, inner loop looks up Table B via index • Hash Join: In-memory hash table is built from Table A on the join key • Sort-Merge Join: Both tables are sorted by join key, then merged in a single coordinated sequential scan.

23
Senior#Databases & SQL

What is a Deadlock and how do databases detect and resolve them?

A deadlock is a circular lock wait dependency where Transaction A waits for a resource locked by Transaction B, and Transaction B waits for a resource locked by Transaction A: Detection: The database maintains a Wait-For Graph.

24
Most AskedSeniorCode#sql-databases#Advanced Internals

What are Pessimistic Locking vs Optimistic Locking?

Pessimistic Locking: Assumes conflicts will happen • Other transactions attempting to modify the row are blocked until commit • Optimistic Locking: Assumes conflicts are rare • Adds a version_number column.

25
Senior#sql-databases#Advanced Internals

What is Table Partitioning and Partition Pruning?

Table Partitioning divides a multi-million row table into physical child tables based on a key (Range, List, Hash): Partition Pruning: During query execution, the optimizer inspects the query WHERE clause and automatically skips reading partition files that.

26
Most AskedSenior#sql-databases#Advanced Internals

What is a Covering Index and how does it eliminate Table Lookups?

A covering index contains all the columns needed to satisfy a query in its index tree (using index keys or INCLUDE (colA, colB)): The database retrieves all requested data directly from the index leaf nodes without touching the physical table heap pages • Results in Index-Only Scans, eliminating expensive random disk I/O.

27
Senior#Databases & SQL

What is SARGability (Search Argument Able) in SQL queries?

A query is SARGable if the optimizer can leverage an index range seek: Non-SARGable (Bad): Wrapping indexed columns in functions disables the index! • SARGable (Good): Keep the column naked.

28
Senior#sql-databases#Advanced Internals

What are Phantom Reads vs Non-Repeatable Reads?

Non-Repeatable Read: Focuses on modifications/updates to an existing row • Phantom Read: Focuses on inserts/deletions affecting a range.

29
Senior#System Design#Databases & SQL

What is Two-Phase Commit (2PC) in Distributed Databases?

Guarantees atomic transactions across multiple distributed database nodes: Prepare Phase: Coordinator asks all participant nodes if they can commit • Commit Phase: If all vote commit, coordinator sends GLOBALCOMMIT • Drawback: Blocking protocol; if coordinator crashes mid-commit, participants remain locked in doubt.

30
Senior#Databases & SQL

What is Database Connection Starvation and how do you size Connection Pools?

Assigning 1,000 connections to a database with 16 CPU cores causes connection starvation: CPU spends 90% of its time context switching between 1,000 threads rather than executing queries! • HikariCP Formula for Pool Sizing.

31
Senior#sql-databases#Advanced Internals

How do you optimize Deep Pagination (`OFFSET 1000000 LIMIT 10`)?

Traditional OFFSET scans and discards 1,000,000 rows: Keyset Pagination (Seek Method).

32
Senior#Databases & SQL

What is Write Amplification in Relational Databases?

The ratio of bytes written to physical storage compared to the logical bytes written by the user: Inserting a 100-byte row into a table with 6 indexes • Writes to Table Heap (16 KB page) • Writes to 6 separate B-Tree Index pages (6 \times 16\text{ KB}) • Writes to Write-Ahead Log (WAL / Redo log).

33
Senior#sql-databases#Advanced Internals

What is the difference between Optimistic Concurrency Control (OCC) and Multi-Version Concurrency Control (MVCC)?

MVCC: Database engine architecture where updates create new versions of rows, allowing concurrent readers to read consistent snapshots without • OCC: Application-level design pattern using version numbers or timestamps to detect conflicts before committing updates without holding locks.

34
Senior#System Design#Databases & SQL

What is Database Sharding (Horizontal Partitioning) and what are its trade-offs?

Splitting a database across multiple independent physical servers: Pros: Unlimited horizontal storage and write capacity scaling • Cons: Distributed transactions across shards become slow/complex, cross-shard joins are impossible without application mediation, and.

35
Most AskedSenior#Databases & SQL

When should you choose a Relational SQL Database over NoSQL?

Strict Financial / Transactional Consistency: Banking, payments, ledger systems requiring ACID guarantees • Complex Entity Relationships: Systems requiring multi-table joins and relational integrity enforcement (Users, Roles, Permissions, Orders).

36
SeniorCode#Databases & SQL

SQL Window Functions: `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, `LEAD()`, and `LAG()`.

Window functions perform calculations across a set of table rows related to the current row without collapsing the rows into a single group like GROUP BY does: ROWNUMBER(): Assigns a unique sequential integer (1, 2, 3, 4) to each row within a partition • RANK(): Assigns ranks with gaps for ties (1, 2, 2, 4).

37
Senior#sql-databases#Advanced Internals

Common Table Expressions (CTEs) vs Subqueries vs Temporary Tables.

Subquery: Inline query inside FROM or WHERE • CTE (WITH .. • Temporary Tables (CREATE TEMP TABLE ...): Persists across multiple queries in a session.

38
SeniorCode#Databases & SQL#Data Structures

Recursive CTEs: Querying Trees and Hierarchies in SQL.

A Recursive CTE references itself to traverse hierarchical data (organization charts, category trees, bill of materials) in pure SQL without procedural code loops: Anchor Member: Initial query that selects the root nodes • Recursive Member: Joins the CTE with the table to select child nodes until no rows remain.

39
Senior#Databases & SQL

Database Normalization: 1NF through BCNF and Intentional Denormalization.

Normalization eliminates data redundancy and prevents update/delete anomalies: 1NF: Atomic values; no repeating groups or comma-separated lists in a single cell • 2NF: In 1NF and all non-key columns depend on the entire primary key (eliminates partial key dependency).

40
SeniorCode#Databases & SQL

SQL Joins Deep Dive: Anti-Joins (`NOT EXISTS` vs `NOT IN`).

Inner Join: Returns rows with matching keys in both tables • Left Outer Join: Returns all rows from left table, with NULLs for non-matching right rows • Anti-Join: Finds records in Table A that have no matching record in Table B • Performance Rule: Prefer NOT EXISTS over NOT IN!.

41
Most AskedSenior#Databases & SQL#Data Structures

B-Tree Indexes and the Leftmost Prefix Rule.

A B-Tree (Balanced Tree) index keeps keys sorted in logarithmic time O(\log N) for lookups, range scans, and sorting: Composite Index (A, B, C): Can accelerate queries filtering on • WHERE A = 1 • WHERE A = 1 AND B = 2 • WHERE A = 1 AND B = 2 AND C = 3.

42
Most AskedSeniorCode#sql-databases#Advanced Internals

Covering Indexes & Index-Only Scans.

In normal index lookups, the database finds the matching row pointer in the B-Tree index, then performs a random disk read (Heap Fetch) to read remaining columns from the table.: Covering Index: An index that contains every column requested by the query (via composite keys or the INCLUDE clause).

43
Most AskedSenior#State Management#Databases & SQL

ACID Transactions: Deep Dive into Write-Ahead Logging (WAL).

ACID guarantees transactional reliability: A (Atomicity): All operations succeed, or all are rolled back • C (Consistency): State transitions must satisfy all constraints and foreign keys • I (Isolation): Concurrent transactions do not interfere with each other.

44
Senior#Databases & SQL

Transaction Isolation Levels and Concurrency Anomalies.

SQL-92 defines four transaction isolation levels to balance consistency against concurrency: Read Uncommitted: Suffers from Dirty Reads (reading uncommitted changes from another transaction that might roll back).

45
Senior#sql-databases#Advanced Internals

Concurrency Control: Optimistic vs Pessimistic Locking.

Pessimistic Locking (SELECT .. • Optimistic Locking: No locks acquired during reading.

46
Senior#Databases & SQL

Database Deadlocks: Detection and Resolution.

A Deadlock occurs when Transaction 1 holds Lock A and waits for Lock B, while Transaction 2 holds Lock B and waits for Lock A: Detection: The database engine runs background deadlock detection (evaluating a Wait-For Graph for cycles) and kills the transaction with lower.

47
Senior#System Design#Databases & SQL

Database Sharding: Horizontal Partitioning Strategies.

When a single database server exceeds CPU, RAM, or storage capacity, data is split across multiple independent database nodes: Range-Based Sharding: Partitioning by ID or Date ranges (e.g. Shard 1: IDs 1-1M; Shard 2: IDs 1M-2M) • Hash-Based Sharding: Applying a hash function hash(userid) % numshards.

48
Senior#sql-databases#Advanced Internals

Primary-Replica Topology and Replication Lag Mitigation.

Primary handles all WRITE operations and streams changes to Read Replicas • Replication Lag: Asynchronous replication introduces a delay (\Delta t \approx 50\text{ms} - 5\text{s}) where replicas lag behind the primary.

49
SeniorCode#Databases & SQL

SQL Injection Prevention: Prepared Statements vs Dynamic SQL.

SQL Injection occurs when untrusted user input is concatenated into an SQL string, allowing attackers to manipulate query syntax.: Prepared Statements: Separate query structure from data values.

50
Senior#Databases & SQL

Database Connection Pooling: Sizing and Leak Prevention.

Creating a new database connection requires TCP handshakes, TLS negotiation, authentication, and allocating backend server processes (consuming ~5-10MB RAM per connection in Postgres).: Connection Pools (HikariCP, PgBouncer) maintain a warm pool of reusable connections.