50 Topics
Chapter•480 Minutes

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?

Difficulty:EasyTopic:Database Architecture

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

Data Model

Relational Tables vs Key-Value / Document / Graph

SQL uses strict normalized schema tables; NoSQL uses flexible dynamic documents.

Scaling

Vertical (Scale-Up) vs Horizontal (Scale-Out)

SQL scales via larger hardware resources; NoSQL scales by adding nodes to a cluster.

Guarantees

ACID vs BASE (Eventually Consistent)

SQL focuses on immediate consistency; NoSQL often prioritizes high availability.

Key Takeaways
  • 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?

Difficulty:EasyTopic:Core Concepts

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.
Key Takeaways
  • 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?

Difficulty:EasyTopic:Schema Design

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 NULL values (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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Engine Internals

Although an SQL query is written starting with SELECT, the database engine processes clauses in a distinct logical order to construct result sets.

Logical SQL Execution Pipeline
Key Takeaways
  • 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?

Difficulty:EasyTopic:Core Filtering

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(), or COUNT().
  • HAVING: Filters aggregated groups after the GROUP BY step finishes computing group statistics.
Combining WHERE and HAVING in a Single Query
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 groups

WHERE filters out inactive employees before computing department counts; HAVING filters out departments with 5 or fewer active employees.

Key Takeaways
  • 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.

Difficulty:EasyTopic:Relational Operations

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).
Key Takeaways
  • 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?

Difficulty:EasyTopic:Data Management

These commands clear records or schema definitions with varying performance and transactional characteristics.

DELETE vs TRUNCATE vs DROP

DELETE

DML | Row-by-Row | Slow | Rollbackable

Fires triggers, logs individual row deletions in transaction WAL.

TRUNCATE

DDL | Page Allocation Reset | Fast

Deallocates data pages directly, bypasses row triggers.

DROP

DDL | Schema Removal | Destructive

Removes data, indexes, constraints, and table metadata from dictionary.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Core Engine

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.

Handling NULL safely with COALESCE
-- 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.

Key Takeaways
  • Arithmetic operations involving NULL return NULL (100 + NULL = NULL).

  • Always use IS NULL or COALESCE() when comparing columns that permit nullability.

Q9: How do GROUP BY and Aggregate Functions work, and how are NULLs handled?

Difficulty:EasyTopic:Aggregations

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 containing NULL values.
  • COUNT(column_name) counts only non-null values in that column.
  • SUM(), AVG(), MIN(), and MAX() automatically ignore NULL values during calculation.
Key Takeaways
  • 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?

Difficulty:EasyTopic:Set Operations

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.
High-Performance Set Merging
-- 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.

Key Takeaways
  • 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.

Q11: What are the types of subqueries (Scalar, Multi-row, Correlated)?

Difficulty:MediumTopic:Subqueries

A subquery is an inner query nested within an outer SELECT, INSERT, UPDATE, or DELETE statement.

  • Scalar Subquery: Returns a single value (1 row, 1 column). Can be used anywhere expressions are allowed.
  • Multi-Row Subquery: Returns multiple rows in a single column. Used with operators like IN, ANY, or ALL.
  • Correlated Subquery: References columns from the outer query. The subquery executes iteratively once for every row processed by the outer query, which can impair performance on large datasets.
Correlated Subquery Example
-- Find employees earning more than their department average
SELECT e.employee_id, e.first_name, e.salary, e.department_id
FROM employees e
WHERE e.salary > (
    SELECT AVG(sub.salary)
    FROM employees sub
    WHERE sub.department_id = e.department_id -- Correlation link
);

The inner query re-calculates average department salary for each candidate row of the outer employee loop.

Key Takeaways
  • Correlated subqueries evaluate repeatedly for each outer candidate row.

  • Convert correlated subqueries to explicit JOINs or CTEs with window functions to optimize query performance.

Q12: What is the difference between EXISTS and IN operators?

Difficulty:MediumTopic:Query Semantics
  • IN: Evaluates full inner subquery result lists before matching values against outer query expressions. If the subquery set contains NULL values, NOT IN queries can evaluate to UNKNOWN and return zero rows.
  • EXISTS: Uses semi-join short-circuit logic. It checks for the existence of matching rows and returns TRUE as soon as a single match is found, ignoring subsequent rows.
Key Takeaways
  • EXISTS utilizes short-circuit processing, stopping evaluation immediately upon finding a matching row.

  • Be careful with NOT IN if the target subquery set contains NULL values.

Q13: What is the difference between a Standard View and a Materialized View?

Difficulty:MediumTopic:Database Objects
  • 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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Advanced SQL

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).

Recursive CTE for Organizational Hierarchy Retrieval
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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Window Functions

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.

Comparing Employee Salary against Department Average
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.

Key Takeaways
  • Window functions compute set values without collapsing individual table rows.

  • Use PARTITION BY to divide records into calculation windows and ORDER BY to set logical ordering.

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

Difficulty:MediumTopic:Ranking Functions

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)

Values

[100, 100, 90, 80]

Target ordered salary list containing duplicate top values.

ROW_NUMBER()

[1, 2, 3, 4]

Non-repeating sequential assignment.

RANK()

[1, 1, 3, 4]

Ties share rank 1; position 2 is skipped.

DENSE_RANK()

[1, 1, 2, 3]

Ties share rank 1; next rank continues strictly sequentially.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Practical SQL

There are two common ways to solve this classic interview question: using DENSE_RANK() or using an offset subquery.

Robust Nth Highest Salary Query
-- 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-1

DENSE_RANK correctly handles duplicate salaries without skipping rank numbers.

Key Takeaways
  • DENSE_RANK() handles duplicate salary values safely without missing ranks.

  • Always include DISTINCT or group partitions when selecting Nth values.

Q18: How do LEAD() and LAG() window functions work?

Difficulty:MediumTopic:Positional Windows

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.
Calculating Month-over-Month Sales Growth
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.

Key Takeaways
  • 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?

Difficulty:MediumTopic:Data Cleanup

To remove duplicates while preserving one original record, use a CTE containing ROW_NUMBER() partitioned by duplicate key attributes.

Safely Removing Duplicates with ROW_NUMBER()
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.

Key Takeaways
  • 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)?

Difficulty:MediumTopic:Normalization

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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Schema Design

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.

Key Takeaways
  • 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.

Difficulty:MediumTopic: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.
Key Takeaways
  • 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?

Difficulty:AdvancedTopic:Transactions

SQL defines four standard transaction isolation levels to balance concurrency against data consistency anomalies.

Concurrency Read Anomalies

  1. Dirty Read: Reading uncommitted changes made by another concurrent transaction.
  2. Non-Repeatable Read: Re-reading the same record yields modified values because another committed transaction updated it.
  3. Phantom Read: Re-running a range query returns newly inserted rows committed by another transaction.

Isolation Levels & Permitted Anomalies

Read Uncommitted

Dirty Read | Non-Repeatable Read | Phantom Read

Maximum concurrency, no isolation guarantees.

Read Committed

Non-Repeatable Read | Phantom Read

Prevents dirty reads. Common default in PostgreSQL and SQL Server.

Repeatable Read

Phantom Read (in some engines)

Ensures read locks remain held until transaction completion.

Serializable

Strict Isolation (Zero Anomalies)

Executes transactions sequentially via lock ranges or serializability checks.

Key Takeaways
  • 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?

Difficulty:AdvancedTopic:Indexing Mechanics
  • B-Tree Index: A self-balancing search tree structure that keeps indexed data sorted. It efficiently processes exact equality matches (=), range scans (>, <, BETWEEN), and ORDER BY operations 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.
Key Takeaways
  • 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?

Difficulty:MediumTopic:Indexing
  • 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.
Key Takeaways
  • 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?

Difficulty:AdvancedTopic:Optimization
  • 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.
Creating a Covering Index with Included Columns
-- 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.

Key Takeaways
  • 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?

Difficulty:AdvancedTopic:Optimization

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 Index
  • WHERE col1 = x AND col2 = y $\rightarrow$ Uses Index
  • WHERE col2 = y AND col3 = z $\rightarrow$ Cannot Use Index (Missing leftmost prefix col1)
Key Takeaways
  • 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?

Difficulty:AdvancedTopic:Performance Tuning

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

  1. Wrapping indexed columns in functions: WHERE YEAR(created_at) = 2026 (Not SARGable).
  2. Wildcards at the start of LIKE patterns: WHERE name LIKE '%smith' (Not SARGable).
  3. Implicit Type Conversion: Comparing string columns against integer values directly.
  4. Arithmetic on indexed columns: WHERE salary * 12 > 100000 (Not SARGable).
Converting Non-SARGable Queries into SARGable Queries
-- 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.

Key Takeaways
  • Avoid wrapping indexed columns in scalar functions within WHERE clauses.

  • Use clear range bounds instead of function transformations to keep queries SARGable.

Q29: How do you analyze an SQL query execution plan using EXPLAIN?

Difficulty:AdvancedTopic:Diagnostics

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) vs Index 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.
Key Takeaways
  • EXPLAIN ANALYZE executes 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?

Difficulty:AdvancedTopic:Concurrency Control

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.

Circular Deadlock Condition
Key Takeaways
  • 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.