Complete Interview Questions & Answer Bank
50 curated SQL technical interview questions ranging from fundamental syntax and database design to advanced analytical window functions, query execution plans, and concurrency control.
Q1: What is the difference between SQL (Relational) and NoSQL (Non-Relational) databases?
SQL databases are relational, structured, and enforce a predefined schema. They store data in tables composed of rows and columns, leveraging ACID properties to guarantee transactional consistency.
NoSQL databases are non-relational, schema-flexible, and designed for horizontal scalability across distributed clusters. They utilize dynamic data models including Key-Value pairs, Document stores (JSON/BSON), Wide-Column stores, and Property Graphs.
SQL vs NoSQL Architectural Comparison
Relational Tables vs Key-Value / Document / Graph
SQL uses strict normalized schema tables; NoSQL uses flexible dynamic documents.
Vertical (Scale-Up) vs Horizontal (Scale-Out)
SQL scales via larger hardware resources; NoSQL scales by adding nodes to a cluster.
ACID vs BASE (Eventually Consistent)
SQL focuses on immediate consistency; NoSQL often prioritizes high availability.
SQL databases excel at complex JOIN queries and strict transactional consistency (ACID).
NoSQL databases excel at handling unstructured or rapidly changing data at massive distributed scale.
Q2: What are DDL, DML, DCL, TCL, and DQL in SQL?
SQL statements are categorized into five sublanguages based on operational scope:
- DDL (Data Definition Language): Defines and alters schema structures. Commands:
CREATE,ALTER,DROP,TRUNCATE,RENAME. - DML (Data Manipulation Language): Modifies stored data rows. Commands:
INSERT,UPDATE,DELETE,MERGE. - DQL (Data Query Language): Retrieves records from schemas. Command:
SELECT. - DCL (Data Control Language): Manages permissions and administrative privileges. Commands:
GRANT,REVOKE. - TCL (Transaction Control Language): Manages atomic transactional changes. Commands:
COMMIT,ROLLBACK,SAVEPOINT.
DDL alters schema metadata; DML and DQL operate directly on table data rows.
TCL manages state persistence across transactions; DCL enforces security permissions.
Q3: What are the differences between Primary Key, Foreign Key, and Unique Key constraints?
Keys enforce entity integrity and relationship constraints within relational schemas:
- Primary Key: Uniquely identifies each record in a table. Enforces non-nullability and uniqueness. A table can have only one Primary Key (which can be composite).
- Unique Key: Ensures all values in a column or column group are distinct. Allows one or more
NULLvalues (database dependent). - Foreign Key: Maintains referential integrity by linking a column in a child table to the Primary Key or Unique Key of a parent table.
A table has exactly one Primary Key, which strictly forbids NULL values.
Foreign Keys enforce referential integrity across relational boundaries.
Q4: What is the logical execution order of an SQL query?
Although an SQL query is written starting with SELECT, the database engine processes clauses in a distinct logical order to construct result sets.
WHERE evaluates before GROUP BY and aggregations, whereas HAVING evaluates after GROUP BY.
Column aliases defined in SELECT cannot be used directly in WHERE or HAVING clauses.
Q5: What is the difference between the WHERE and HAVING clauses?
The fundamental difference lies in aggregation pipeline execution timing:
- WHERE: Filters individual records before group aggregations occur. It cannot evaluate aggregate functions like
SUM(),AVG(), orCOUNT(). - HAVING: Filters aggregated groups after the
GROUP BYstep finishes computing group statistics.
SELECT department_id, COUNT(*) AS employee_count
FROM employees
WHERE status = 'ACTIVE' -- Filters raw rows first
GROUP BY department_id
HAVING COUNT(*) > 5; -- Filters aggregated groupsWHERE filters out inactive employees before computing department counts; HAVING filters out departments with 5 or fewer active employees.
WHERE operates on individual records; HAVING operates on aggregated groups.
Filtering records as early as possible with WHERE improves performance by reducing group calculation payload size.
Q6: Explain INNER, LEFT, RIGHT, FULL, and CROSS JOINs with examples.
JOIN clauses combine columns from one or more tables using related attributes:
- INNER JOIN: Returns only matching records existing in both tables.
- LEFT (OUTER) JOIN: Returns all records from the left table and matching records from the right table. Unmatched right values return
NULL. - RIGHT (OUTER) JOIN: Returns all records from the right table and matching left records.
- FULL (OUTER) JOIN: Returns all records when a match exists in either left or right table.
- CROSS JOIN: Produces the Cartesian product of both tables (N × M rows).
LEFT JOIN guarantees all rows from the primary left table are retained.
CROSS JOIN produces N * M rows and should be used with caution on large dataset sizes.
Q7: What is the difference between DELETE, TRUNCATE, and DROP commands?
These commands clear records or schema definitions with varying performance and transactional characteristics.
DELETE vs TRUNCATE vs DROP
DML | Row-by-Row | Slow | Rollbackable
Fires triggers, logs individual row deletions in transaction WAL.
DDL | Page Allocation Reset | Fast
Deallocates data pages directly, bypasses row triggers.
DDL | Schema Removal | Destructive
Removes data, indexes, constraints, and table metadata from dictionary.
TRUNCATE is a high-performance DDL operation that resets identity seeds and deallocates data pages.
DELETE supports conditional WHERE filtering and logs individual row removals.
Q8: How does SQL evaluate NULL values and Three-Valued Logic?
NULL in SQL represents an unknown or missing value, not zero or an empty string ('').
Because NULL is unknown, direct equality comparisons (field = NULL or NULL = NULL) evaluate to UNKNOWN, not TRUE or FALSE. SQL utilizes Three-Valued Logic (TRUE, FALSE, UNKNOWN).
To check for missing values, use IS NULL or IS NOT NULL. Functions like COALESCE(col, fallback) or NVL() replace NULL values with predefined defaults.
-- Incorrect: evaluates to UNKNOWN for nulls
SELECT * FROM employees WHERE commission_pct = NULL;
-- Correct: handles null check explicitly
SELECT * FROM employees WHERE commission_pct IS NULL;
-- Replacing null values in calculations
SELECT employee_id, salary + COALESCE(commission_pct, 0) AS total_comp
FROM employees;COALESCE returns the first non-null argument, guaranteeing arithmetic operations do not resolve to NULL.
Arithmetic operations involving NULL return NULL (
100 + NULL = NULL).Always use
IS NULLorCOALESCE()when comparing columns that permit nullability.
Q9: How do GROUP BY and Aggregate Functions work, and how are NULLs handled?
GROUP BY collapses set rows sharing common values into summary groups. Aggregate functions (SUM(), AVG(), COUNT(), MIN(), MAX()) summarize each group.
NULL Handling in Aggregates
COUNT(*)counts all rows, including rows containingNULLvalues.COUNT(column_name)counts only non-null values in that column.SUM(),AVG(),MIN(), andMAX()automatically ignoreNULLvalues during calculation.
COUNT(*)includes NULL rows;COUNT(column)ignores NULL entries.All non-aggregated columns listed in the SELECT clause must be included in the GROUP BY clause.
Q10: What is the difference between UNION and UNION ALL?
Both operators merge result sets from multiple SELECT queries into a single output set. They require matching column counts and compatible data types across positional indices.
- UNION: Combines result sets and performs an implicit duplicate elimination pass (sorting or hashing output records).
- UNION ALL: Concatenates result sets directly without deduplication, preserving all records.
-- UNION ALL avoids expensive sorting overhead
SELECT customer_id, city FROM domestic_customers
UNION ALL
SELECT customer_id, city FROM international_customers;Use UNION ALL when datasets are known to be mutually exclusive or when keeping duplicate rows is acceptable, avoiding costly distinct sorting operations.
UNION performs duplicate removal; UNION ALL retains all rows directly.
UNION ALL offers superior performance because it avoids expensive memory sorting or hash deduplication operations.
Q12: What is the difference between EXISTS and IN operators?
- IN: Evaluates full inner subquery result lists before matching values against outer query expressions. If the subquery set contains
NULLvalues,NOT INqueries can evaluate toUNKNOWNand return zero rows. - EXISTS: Uses semi-join short-circuit logic. It checks for the existence of matching rows and returns
TRUEas soon as a single match is found, ignoring subsequent rows.
EXISTS utilizes short-circuit processing, stopping evaluation immediately upon finding a matching row.
Be careful with
NOT INif the target subquery set containsNULLvalues.
Q13: What is the difference between a Standard View and a Materialized View?
- Standard View: A virtual table backed by a saved SQL query definition. It stores no physical data on disk. When queried, the underlying SQL expression executes in real time.
- Materialized View: A persisted table structure containing physical query execution results. It dramatically speeds up complex analytical aggregation workloads, but requires periodic manual or triggered refresh cycles (
REFRESH MATERIALIZED VIEW) to stay in sync with base table changes.
Standard views act as virtual queries; Materialized Views persist physical data records on disk.
Materialized Views require explicit refresh management to balance query performance against data freshness.
Q14: What is a Common Table Expression (CTE) and when should you use it?
A Common Table Expression (CTE) is a temporary, named result set defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement using the WITH clause.
CTEs improve code readability compared to deeply nested subqueries and support Recursive CTEs, which enable hierarchical tree traversals (e.g., organizational charts or bill-of-materials structures).
WITH RECURSIVE OrgChart AS (
-- Anchor Member: Top level CEO
SELECT employee_id, manager_id, first_name, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
-- Recursive Member: Join subordinates
SELECT e.employee_id, e.manager_id, e.first_name, o.depth + 1
FROM employees e
INNER JOIN OrgChart o ON e.manager_id = o.employee_id
)
SELECT * FROM OrgChart ORDER BY depth;The anchor query establishes the tree root node; the recursive part iteratively joins child records until no further matches are found.
CTEs split complex queries into clean, maintainable logic blocks.
Recursive CTEs allow efficient processing of graph and tree structures natively in SQL.
Q15: What are Window Functions and how do they differ from GROUP BY?
Window functions perform calculations across a set of table rows related to the current query row using the OVER() clause.
Unlike GROUP BY, which collapses grouped rows into a single summary output row, window functions compute aggregate or positional values while preserving individual row identities.
SELECT
employee_id,
department_id,
salary,
AVG(salary) OVER(PARTITION BY department_id) AS dept_avg_salary
FROM employees;Every individual employee row is preserved while calculating the aggregate department average alongside it.
Window functions compute set values without collapsing individual table rows.
Use
PARTITION BYto divide records into calculation windows andORDER BYto set logical ordering.
Q16: What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?
All three are ranking window functions, but they handle tied values differently:
ROW_NUMBER(): Assigns a unique, sequential integer to every row (1, 2, 3, 4, 5). Ties receive arbitrary unique numbers.RANK(): Assigns identical rank values to tied rows, but skips subsequent ranks to reflect tie counts (1, 2, 2, 4, 5).DENSE_RANK(): Assigns identical rank values to tied rows without skipping subsequent numbers (1, 2, 2, 3, 4).
Ranking Behavior Comparison (Tied Values at 100)
[100, 100, 90, 80]
Target ordered salary list containing duplicate top values.
[1, 2, 3, 4]
Non-repeating sequential assignment.
[1, 1, 3, 4]
Ties share rank 1; position 2 is skipped.
[1, 1, 2, 3]
Ties share rank 1; next rank continues strictly sequentially.
Use
DENSE_RANK()to find Nth highest values without missing sequential rank numbers.Use
ROW_NUMBER()for pagination or non-deterministic duplicate row removal.
Q17: How do you find the Nth highest salary in a table?
There are two common ways to solve this classic interview question: using DENSE_RANK() or using an offset subquery.
-- Method 1: Using Window Functions (Handles tied salaries correctly)
WITH RankedSalaries AS (
SELECT employee_id, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) as rnk
FROM employees
)
SELECT DISTINCT salary
FROM RankedSalaries
WHERE rnk = 2; -- Change N here
-- Method 2: Generic OFFSET Subquery (MySQL / Postgres)
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1; -- OFFSET N-1DENSE_RANK correctly handles duplicate salaries without skipping rank numbers.
DENSE_RANK()handles duplicate salary values safely without missing ranks.Always include
DISTINCTor group partitions when selecting Nth values.
Q18: How do LEAD() and LAG() window functions work?
LEAD() and LAG() are positional window functions used to inspect adjacent row data relative to the current row without performing a self-join.
LAG(col, offset, default): Accesses column values from preceding rows.LEAD(col, offset, default): Accesses column values from subsequent rows.
SELECT
sale_month,
revenue,
LAG(revenue, 1, 0.0) OVER (ORDER BY sale_month) AS prev_month_revenue,
revenue - LAG(revenue, 1, 0.0) OVER (ORDER BY sale_month) AS mom_change
FROM monthly_sales;LAG retrieves the previous month's revenue to compute month-over-month differences directly in the current row.
LAG inspects previous records; LEAD inspects upcoming records.
They are ideal for calculating month-over-month trends, running totals, and time-series differences.
Q19: How do you identify and remove duplicate rows from a table?
To remove duplicates while preserving one original record, use a CTE containing ROW_NUMBER() partitioned by duplicate key attributes.
WITH DuplicateCTE AS (
SELECT id, email,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY id ASC
) AS row_num
FROM users
)
DELETE FROM users
WHERE id IN (
SELECT id FROM DuplicateCTE WHERE row_num > 1
);ROW_NUMBER assigns row_num = 1 to the first instance of each email. Rows with row_num > 1 are duplicates and get removed.
Partitioning by duplicate key attributes identifies redundant records reliably.
Always filter using primary keys or row IDs to prevent deleting entire matching record groups.
Q20: What is Database Normalization and its forms (1NF, 2NF, 3NF, BCNF)?
Normalization structures database schemas to minimize data redundancy and prevent insertion, update, and deletion anomalies.
- 1NF (First Normal Form): Ensures atomic column values (no multi-valued lists or nested sets) and unique row keys.
- 2NF (Second Normal Form): Satisfies 1NF and removes partial dependencies (non-key attributes must depend on the entire primary key).
- 3NF (Third Normal Form): Satisfies 2NF and removes transitive dependencies (non-key attributes must depend only on primary key attributes).
- BCNF (Boyce-Codd Normal Form): A stricter variant of 3NF where every determinant must be a candidate key.
1NF enforces atomicity; 2NF removes partial key dependencies; 3NF removes transitive dependencies.
Higher normalization reduces data redundancy, but can require more JOINs when querying.
Q21: What is Denormalization and when should it be applied?
Denormalization intentionally introduces redundant data or pre-aggregated summary columns into a normalized schema.
While normalization optimizes data integrity and write performance, denormalization optimizes read latency in high-scale analytical databases (OLAP) or read-heavy applications by minimizing expensive JOIN operations.
Denormalization improves read query speeds at the expense of storage space and potential write anomalies.
Commonly used in data warehouses, star schema topologies, and read-heavy analytics systems.
Q22: Explain the ACID properties of relational database transactions.
ACID guarantees that database transactions are executed reliably:
- Atomicity: 'All-or-Nothing' execution. If any statement in a transaction fails, all changes are fully rolled back.
- Consistency: Ensures transactions transition the database from one valid state to another, preserving all schema constraints.
- Isolation: Concurrent transactions execute without interfering with one another's uncommitted state.
- Durability: Once a transaction commits, its changes persist permanently on disk even during system crashes.
ACID properties guarantee financial-grade reliability for transaction processing systems.
Atomicity relies on write-ahead logging (WAL) to support rollback operations.
Q23: What are Transaction Isolation Levels and Read Anomalies?
SQL defines four standard transaction isolation levels to balance concurrency against data consistency anomalies.
Concurrency Read Anomalies
- Dirty Read: Reading uncommitted changes made by another concurrent transaction.
- Non-Repeatable Read: Re-reading the same record yields modified values because another committed transaction updated it.
- Phantom Read: Re-running a range query returns newly inserted rows committed by another transaction.
Isolation Levels & Permitted Anomalies
Dirty Read | Non-Repeatable Read | Phantom Read
Maximum concurrency, no isolation guarantees.
Non-Repeatable Read | Phantom Read
Prevents dirty reads. Common default in PostgreSQL and SQL Server.
Phantom Read (in some engines)
Ensures read locks remain held until transaction completion.
Strict Isolation (Zero Anomalies)
Executes transactions sequentially via lock ranges or serializability checks.
Higher isolation levels prevent more read anomalies, but reduce concurrent transaction throughput.
Read Committed is the standard default isolation level in many enterprise relational database engines.
Q24: How do B-Tree and Hash Indexes work internally?
- B-Tree Index: A self-balancing search tree structure that keeps indexed data sorted. It efficiently processes exact equality matches (
=), range scans (>,<,BETWEEN), andORDER BYoperations in logarithmic time ($O(\log N)$). - Hash Index: Uses hash tables to map key values to row locations. It provides constant-time $O(1)$ lookups for equality checks (
=), but cannot support range queries or ordering operations.
B-Trees are the default index type because they support both range lookups and equality matches efficiently.
Hash indexes offer fast equality lookups, but do not support range scans or sorting.
Q25: What is the difference between Clustered and Non-Clustered Indexes?
- Clustered Index: Determines the physical storage order of data rows on disk. Because rows can only be ordered one way, a table can have only one Clustered Index (typically assigned to the Primary Key).
- Non-Clustered Index: A secondary structure stored separately from data rows. It contains indexed column keys and pointers (row IDs or clustered key values) that reference the underlying table rows.
Clustered indexes physically organize table rows on disk; a table can have only one.
Non-clustered indexes store column keys with pointers back to table data pages.
Q26: What is a Covering Index, and how does Index Seek differ from Index Scan?
- Index Seek: The database engine uses index tree structures to jump directly to specific matching rows. Highly efficient.
- Index Scan: The engine traverses the entire index leaf structure row by row. Less efficient than a seek.
- Covering Index: A non-clustered index that includes all columns referenced by a query (filtering, joining, and selected output columns). It allows the engine to return results directly from the index without reading table data pages.
-- Covering index including extra payload columns
CREATE INDEX idx_orders_customer_covering
ON orders (customer_id, order_date)
INCLUDE (total_amount, order_status);
-- Executing query directly satisfied by index
SELECT total_amount, order_status
FROM orders
WHERE customer_id = 4521
AND order_date >= '2026-01-01';Because all selected and filtered columns exist within the index, the query engine skips reading table data pages entirely.
Index Seeks locate target records directly; Index Scans read through entire index structures.
Covering indexes avoid expensive table lookup operations by serving queries entirely from index pages.
Q27: What is a Composite Index and the Leftmost Prefix Rule?
A composite index spans multiple columns (e.g., INDEX (col1, col2, col3)).
The Leftmost Prefix Rule
The database query planner can use a composite index only if query predicate conditions match column combinations starting from the leftmost column onward.
WHERE col1 = x$\rightarrow$ Uses IndexWHERE col1 = x AND col2 = y$\rightarrow$ Uses IndexWHERE col2 = y AND col3 = z$\rightarrow$ Cannot Use Index (Missing leftmost prefixcol1)
Composite indexes evaluate conditions following the leftmost prefix order.
Place high-cardinality, frequently filtered columns at the beginning of composite index definitions.
Q28: What makes a query SARGable, and what invalidates index usage?
SARGable stands for Search Argument Able. A query is SARGable if the database engine can leverage an index to speed up execution.
Anti-Patterns That Invalidate Index Usage
- Wrapping indexed columns in functions:
WHERE YEAR(created_at) = 2026(Not SARGable). - Wildcards at the start of LIKE patterns:
WHERE name LIKE '%smith'(Not SARGable). - Implicit Type Conversion: Comparing string columns against integer values directly.
- Arithmetic on indexed columns:
WHERE salary * 12 > 100000(Not SARGable).
-- BAD (Non-SARGable): Function forces full table scan
SELECT * FROM orders WHERE DATE(order_timestamp) = '2026-05-10';
-- GOOD (SARGable): Range scan uses index efficiently
SELECT * FROM orders
WHERE order_timestamp >= '2026-05-10 00:00:00'
AND order_timestamp < '2026-05-11 00:00:00';Replacing function calls with explicit range conditions enables index seeks across range values.
Avoid wrapping indexed columns in scalar functions within
WHEREclauses.Use clear range bounds instead of function transformations to keep queries SARGable.
Q29: How do you analyze an SQL query execution plan using EXPLAIN?
The EXPLAIN (or EXPLAIN ANALYZE) command reveals the execution steps chosen by the database query optimizer.
Key Metrics to Analyze
- Scan Types:
Seq Scan/Table Scan(slow) vsIndex Seek/Index Scan(fast). - Join Algorithms:
Nested Loop(good for small sets),Hash Join(good for large unsorted sets),Merge Join(efficient for pre-sorted sets). - Cost Estimates: Startup and total cost measures calculated by database statistics engines.
- Actual Time / Rows: Real execution timings provided by
EXPLAIN ANALYZE.
EXPLAIN ANALYZEexecutes the target query and reports real runtime performance statistics.Look for sequential scans on large tables to identify missing index opportunities.
Q30: What is a Database Deadlock, and how can it be prevented?
A deadlock occurs when two or more concurrent transactions hold locks on separate resources and each waits to acquire a lock held by the other, creating a circular dependency.
Prevent deadlocks by accessing tables in a consistent order across all application transactions.
Keep transactions small and avoid long interactive user prompts during open lock windows.