Mid-level 6 min · March 06, 2026

DBMS Interview Questions — Deadlock Debugging & Index Traps

UPDATE without index caused 100% CPU deadlock cascade in checkout.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • ACID guarantees Atomicity, Consistency, Isolation, Durability — each solves a specific failure mode
  • Normalization reduces redundancy via 1NF→3NF, but denormalization wins in OLAP
  • Clustered index physically sorts rows; non-clustered is a separate pointer structure
  • Isolation levels are a dial: READ COMMITTED for most apps, SERIALIZABLE for financial accuracy
  • Indexes speed reads, slow writes — only index WHERE/JOIN/ORDER BY columns
  • Foreign keys prevent orphan rows but can cascade into performance traps
Plain-English First

A database management system is like a super-organized filing cabinet in a busy hospital. Every patient record, appointment, and prescription is stored in labeled folders (tables), cross-referenced by unique patient IDs (primary keys), and managed by a strict librarian (the DBMS) who makes sure two nurses never overwrite each other's notes at the same time. When an interviewer asks about DBMS, they want to know you understand not just where things are stored, but how they stay consistent, fast, and safe.

Most developers can write a SELECT statement in their sleep. But interviews don't test that — they test whether you understand what happens underneath when that query runs, why your app grinds to a halt under load, or why two users can accidentally corrupt each other's data without any error message. DBMS knowledge is the difference between a developer who writes queries and one who designs systems that survive production.

The real problem is that most learning resources dump definitions at you — ACID, normalization, indexes — without explaining why any of it was invented. Normalization wasn't invented to annoy you with extra joins; it was invented because data duplication causes silent corruption. Transactions weren't invented to slow things down; they were invented because power cuts happen mid-write. Understanding the 'why' is what separates good interview answers from great ones.

By the end of this article you'll be able to explain normalization forms with a concrete example, describe ACID properties with a real scenario an interviewer can't poke holes in, differentiate clustered vs non-clustered indexes in a single sentence, and confidently answer the tricky follow-up questions that trip most candidates up.

ACID Properties — What They Are and Why Every Transaction Needs Them

ACID is the four-part promise a database makes to you every time you run a transaction. Think of it as a bank's promise when you transfer money: either the full transfer happens or nothing does — you'll never lose money into thin air.

Atomicity means the transaction is all-or-nothing. If you're moving £500 from Account A to Account B and the server crashes after the debit but before the credit, atomicity rolls the debit back. No money disappears.

Consistency means the database only moves from one valid state to another. If your schema says 'balance cannot be negative', a consistent database will reject any transaction that violates that — even mid-flight.

Isolation means concurrent transactions don't see each other's dirty work. If two cashiers are processing transactions simultaneously, isolation makes it look like they ran one after the other, not at the same time.

Durability means once the database says 'committed', the data survives a crash. It achieves this through write-ahead logs — it writes the intention to disk before actually doing it.

Interviewers love asking which property is hardest to implement. The answer is Isolation, because perfect isolation requires serialisable transactions which kills performance, so databases let you tune it with isolation levels.

BankTransferTransaction.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-- Scenario: Production-grade bank transfer logic
-- Package: io.thecodeforge.db.transactions

BEGIN TRANSACTION;

    -- Step 1: Debit the sender's account
    -- We assume a CHECK constraint on 'balance >= 0' exists for Consistency
    UPDATE io_thecodeforge.bank_accounts
    SET balance = balance - 500
    WHERE account_id = 'ACC-001';

    -- Step 2: Check the balance explicitly for custom business logic
    -- If this fails, the whole transaction rolls back (Atomicity)
    IF (SELECT balance FROM io_thecodeforge.bank_accounts WHERE account_id = 'ACC-001') < 0
    BEGIN
        ROLLBACK TRANSACTION;
        PRINT 'Transfer failed: insufficient funds. No changes were saved.';
        RETURN;
    END

    -- Step 3: Credit the receiver's account
    UPDATE io_thecodeforge.bank_accounts
    SET balance = balance + 500
    WHERE account_id = 'ACC-002';

COMMIT TRANSACTION;
-- Durability: The DBMS flushes the WAL (Write-Ahead Log) to disk here.
PRINT 'Transfer committed successfully.';
Output
Transfer committed successfully.
-- If ACC-001 had insufficient funds:
Transfer failed: insufficient funds. No changes were saved.
Interview Gold:
When asked 'what is the difference between Atomicity and Durability?', say this: Atomicity is about what happens DURING a transaction (all or nothing), while Durability is about what happens AFTER a commit (it sticks, even through a crash). They're two different time horizons of the same guarantee.
Production Insight
Most production transaction bugs come from broken Isolation, not broken Atomicity.
Non-repeatable reads cause incorrect account balances when two transactions interleave.
Rule: always set isolation level explicitly per transaction, don't rely on defaults.
For high-throughput systems, accept READ COMMITTED and handle missing rows in code.
Key Takeaway
ACID is a four-part contract.
Atomicity + Durability protect against crashes.
Consistency protects against data corruption.
Isolation is the hardest to get right—tune it per use case.

Normalization Explained — From Messy Spreadsheet to Clean Schema

Normalization is the process of restructuring your database tables to eliminate data redundancy and prevent update anomalies. The best way to understand why it exists is to see what happens when you skip it.

Imagine a single Orders table where you store the customer's name, address, and email alongside every order they've ever placed. If a customer moves house, you need to update their address in 50 rows. Miss one? Congratulations, you now have inconsistent data — two 'truths' for the same customer.

Normalization solves this by separating concerns into distinct tables and linking them with keys. There are several normal forms, but interviewers focus on 1NF through 3NF.

1NF (First Normal Form): Every column holds atomic (indivisible) values, and each row is unique. No comma-separated lists in a single cell.

2NF (Second Normal Form): Achieves 1NF AND every non-key column is fully dependent on the entire primary key — not just part of it. This only matters for composite primary keys.

3NF (Third Normal Form): Achieves 2NF AND no non-key column depends on another non-key column (no transitive dependencies). Classic example: storing both ZipCode and City — City depends on ZipCode, not on the primary key directly.

BCNF (Boyce-Codd Normal Form) is a stricter version of 3NF. Interviewers may test whether you know it exists, even if you don't memorise the formal definition.

NormalizationExample.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-- ============================================================
-- AFTER NORMALIZATION: Separated into three clean tables (3NF)
-- Package: io.thecodeforge.db.schema
-- ============================================================

-- Customers table: 3NF compliant, no transitive dependencies
CREATE TABLE io_thecodeforge.customers (
    customer_id   INT PRIMARY KEY,
    customer_name VARCHAR(100) NOT NULL,
    customer_zip  VARCHAR(10)  NOT NULL,
    customer_city VARCHAR(100) NOT NULL 
);

-- Products table: Centralized product definitions
CREATE TABLE io_thecodeforge.products (
    product_id   INT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    unit_price   DECIMAL(10, 2) NOT NULL
);

-- Orders table: Linked via Foreign Keys for Referential Integrity
CREATE TABLE io_thecodeforge.orders (
    order_id    INT PRIMARY KEY,
    customer_id INT NOT NULL REFERENCES io_thecodeforge.customers(customer_id),
    product_id  INT NOT NULL REFERENCES io_thecodeforge.products(product_id),
    quantity    INT NOT NULL,
    order_date  DATE NOT NULL
);

-- If a customer moves, we update ONE row. Zero Risk of Update Anomalies.
UPDATE io_thecodeforge.customers
SET customer_city = 'Manchester', customer_zip = 'M1 1AA'
WHERE customer_id = 42;

SELECT 'Update complete. Data integrity preserved.' AS result;
Output
result
--------------------------------------------
Update complete. Data integrity preserved.
Watch Out:
Interviewers sometimes ask 'should you always normalize to 3NF?' The answer is NO. In read-heavy analytics databases (OLAP), denormalization is often intentional — fewer joins means faster aggregation queries. Always tie your answer to the use case: OLTP (transactional systems) benefits from normalization; OLAP (reporting/analytics) often tolerates or embraces denormalization.
Production Insight
Over-normalized schemas cause massive JOIN chains that kill query throughput.
In one incident, a 10-table join with proper indexes still performed poorly because the DB optimizer chose the wrong join order.
Solution: create materialized views or denormalize summary tables for reporting queries.
Rule: normalize for write integrity; denormalize for read performance — know which one matters more.
Key Takeaway
Normalization prevents update anomalies.
Denormalization prevents read bottlenecks.
Your job is to pick the right balance for the workload.

Indexes — The Phone Book Trick That Makes Queries 1000x Faster

An index is a separate data structure the database maintains alongside your table to make lookups faster. Without an index, a query like WHERE email = 'alice@example.com' forces the database to scan every single row — called a full table scan. With an index on email, the database jumps directly to the matching rows like finding a name in an alphabetically sorted phone book.

The two types interviewers always ask about are clustered and non-clustered indexes.

A clustered index physically reorders the rows in the table to match the index order. Because the rows themselves are the index, you can only have ONE clustered index per table. In most databases, the primary key is automatically the clustered index.

A non-clustered index is a separate structure that stores the indexed column values alongside pointers back to the actual rows. You can have many of these. Think of it as the index pages at the back of a textbook — the book (table) isn't reordered, but the index tells you exactly which page to turn to.

The performance trade-off is real: indexes speed up reads dramatically but slow down writes (INSERT, UPDATE, DELETE) because the database must update the index every time data changes. This is why you don't just index every column — you index the columns that appear in WHERE, JOIN, and ORDER BY clauses on your most frequent queries.

IndexPerformanceDemo.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
-- Scenario: High-traffic user lookup optimization
-- Package: io.thecodeforge.db.indexing

CREATE TABLE io_thecodeforge.user_sessions (
    session_id    BIGINT PRIMARY KEY,  -- Clustered index
    customer_email VARCHAR(255) NOT NULL,
    login_time    DATETIME NOT NULL
);

-- ============================================================
-- ANALYZE: Before adding a non-clustered index
-- ============================================================
EXPLAIN ANALYZE 
SELECT * FROM io_thecodeforge.user_sessions
WHERE customer_email = 'dev@thecodeforge.io';
-- Expect: Sequential Scan (O(N))

-- ============================================================
-- OPTIMIZE: Creating a B-Tree Non-Clustered Index
-- ============================================================
CREATE INDEX idx_user_sessions_email
    ON io_thecodeforge.user_sessions (customer_email);

-- ============================================================
-- VERIFY: After indexing
-- ============================================================
EXPLAIN ANALYZE 
SELECT * FROM io_thecodeforge.user_sessions
WHERE customer_email = 'dev@thecodeforge.io';
-- Expect: Index Seek/Scan (O(log N))
Output
-- EXPLAIN results summarize:
-- Before: Full Table Scan (Cost high, rows scanned: 1M)
-- After: Index Lookup (Cost low, rows scanned: 1)
Pro Tip:
If an interviewer asks 'when would you NOT use an index?', give three cases: (1) Small tables where a full scan is faster than index overhead, (2) Columns with very low cardinality like a boolean 'is_active' — the index barely helps because half the table matches, (3) Tables with extremely high write rates like a real-time event log — the index maintenance cost outweighs the read benefit.
Production Insight
A missing index on a WHERE clause can bring a production system to its knees.
We once saw an UPDATE that scanned 50 million rows because it was missing a composite index on (status, created_at).
The query took 8 seconds and blocked all other transactions waiting for row locks.
Rule: always run EXPLAIN on every new query before merging to production — especially if it touches a hot table.
Key Takeaway
Indexes are trade-offs.
A well-chosen index can turn a 10-second scan into a 1-millisecond seek.
Each extra index slows writes — index only what your queries actually filter on.

Joins, Keys & Isolation Levels — The Questions That Actually Catch People Out

Most candidates can explain INNER JOIN. Fewer can explain why NULL breaks a FOREIGN KEY check or what happens when two transactions read the same row simultaneously. These are the questions that separate solid candidates from exceptional ones.

Transaction isolation levels control how much one transaction can see of another's uncommitted work. The four standard levels (lowest to highest isolation) are: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.

READ UNCOMMITTED allows dirty reads — you can see another transaction's changes before they commit. This is almost never safe. READ COMMITTED (the default in PostgreSQL) means you only see committed data, but a value you read once might change if you read it again in the same transaction (non-repeatable read). REPEATABLE READ (MySQL InnoDB default) guarantees the same value every time you read within a transaction, but phantom rows — new rows that match your WHERE clause — can still appear. SERIALIZABLE is the strictest: transactions execute as if they're running one at a time.

The practical impact: most web apps run fine at READ COMMITTED. Financial systems that require precise calculations (like generating an account statement mid-month) should use REPEATABLE READ or SERIALIZABLE. Higher isolation = more locking = lower throughput.

For keys: a PRIMARY KEY uniquely identifies a row and cannot be NULL. A FOREIGN KEY enforces referential integrity — you cannot add an order for a customer_id that doesn't exist in the customers table, and (depending on your ON DELETE rule) you can't delete a customer who still has orders.

IsolationLevelDemo.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-- Demonstrating Dirty Read Protection
-- Package: io.thecodeforge.db.concurrency

-- Transaction A: Updating stock (Uncommitted)
BEGIN TRANSACTION;
    UPDATE io_thecodeforge.inventory 
    SET stock_count = 0 
    WHERE product_id = 99;

-- Transaction B: Reading under READ COMMITTED
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
    SELECT stock_count FROM io_thecodeforge.inventory WHERE product_id = 99;
    -- Result: 50 (Ignores Transaction A's uncommitted change)
COMMIT;

-- Transaction A fails/rolls back
ROLLBACK;

-- If Transaction B used READ UNCOMMITTED, it would have seen '0',
-- causing a 'Dirty Read' and potentially incorrect business logic.
Output
stock_count
-----------
50 -- Correct: READ COMMITTED prevents phantom data
Interview Gold:
When asked about isolation levels, don't just list them — anchor each one to a real problem it solves or causes: 'READ UNCOMMITTED causes dirty reads. READ COMMITTED stops dirty reads but allows non-repeatable reads. REPEATABLE READ stops both but allows phantom reads. SERIALIZABLE stops all three but is the slowest.' That structure shows you understand consequences, not just definitions.
Production Insight
Using the wrong isolation level can cause subtle data corruption that only shows up under concurrent load.
A financial reconciliation system using READ COMMITTED saw non-repeatable reads that caused inconsistent account snapshot totals.
Switching to REPEATABLE READ for the reconciliation transaction fixed it, at the cost of ~15% throughput drop.
Rule: choose isolation level per transaction, not per database — use the weakest level that guarantees correctness.
Key Takeaway
Isolation levels are a dial between consistency and performance.
Financial accuracy demands SERIALIZABLE.
Most web apps are fine with READ COMMITTED.
Make your choice explicit and test under real concurrency.

Query Optimization & Execution Plans — Reading the Database's Mind

You can write the perfect query, but if the database optimizer decides to scan 10 million rows, your app will crawl. Understanding how to read an execution plan is what transforms a good developer into a senior one. Interviewers love asking you to optimize a slow query — they want to see your thought process, not a magic bullet.

An execution plan shows the steps the database takes to run your query: which indexes it uses, which join algorithms (hash join, nested loop, merge join), and the estimated row counts. The most common red flag is a 'Seq Scan' on a large table — that means you're missing an index or your WHERE clause isn't SARGable (Search ARGument Able).

SARGability is key: wrapping an indexed column in a function like LOWER(email) = 'alice@example.com' makes the index unusable because the database has to evaluate the function for every row. Instead, use LOWER(email) in a functional index, or store the lowercase value.

Other optimizations: avoid SELECT *, use covering indexes, and analyze statistics regularly. A query that ran fine on 1000 rows can blow up on 1 million if the optimizer chooses a different plan due to stale statistics.

QueryOptimizationDemo.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- Problem: Slow query with WHERE LOWER(email) = ?
-- Even if email is indexed, index won't be used (non-SARGable)

-- Before: Full table scan because of function on indexed column
EXPLAIN ANALYZE
SELECT * FROM io_thecodeforge.users
WHERE LOWER(email) = 'dev@thecodeforge.io';
-- Expect: Seq Scan on users (cost=1000..10000)

-- Fix: Create a functional index on LOWER(email)
CREATE INDEX idx_users_lower_email 
    ON io_thecodeforge.users (LOWER(email));

-- After: Index scan now works
EXPLAIN ANALYZE
SELECT * FROM io_thecodeforge.users
WHERE LOWER(email) = 'dev@thecodeforge.io';
-- Expect: Bitmap Index Scan on idx_users_lower_email

-- Alternative fix: Store lowercase email in a separate column and index that
Output
-- Results:
-- Before: Seq Scan, 1600ms, scans 1M rows
-- After: Index Scan, 2ms, scans 1 row
Mental Model: The Execution Plan as a Recipe
  • Each step is an instruction: 'scan this table', 'join these two results', 'sort by column X'.
  • The cost estimate is the time each step takes (in arbitrary units).
  • The actual rows vs estimated rows shows if statistics are stale.
  • You want to see index scans, not sequential scans, on large tables.
Production Insight
A query that runs fine in staging with 10K rows will often choose a different, slower plan in production with 100M rows.
We had a report query that suddenly started taking 30 seconds because the optimizer switched from an index scan to a hash join due to outdated statistics.
Solution: schedule ANALYZE after major data loads, and use pg_hint_plan or query hints to lock in the best plan if necessary.
Rule: always verify execution plans on production-sized data before promoting code.
Key Takeaway
Reading an execution plan is the 1 skill every senior DB engineer must have.
Seq scan on a large table? Missing index or non-SARGable WHERE.
Row count mismatch? Stale statistics.
● Production incidentPOST-MORTEMseverity: high

The Midnight Deadlock Cascade That Took Down Checkout

Symptom
Checkout API timeout errors across all regions; database CPU at 100% with escalating deadlocks.
Assumption
Team assumed it was a traffic spike. But load was normal. Real cause was a single UPDATE query scanning millions of rows.
Root cause
A new feature added an UPDATE on orders without an index on the WHERE clause (status and customer_id). Every update required a full table scan, holding row locks for seconds. As concurrent users hit the same rows, deadlocks cascaded.
Fix
Added a composite index on (status, customer_id). Query time dropped from 4.2s to 3ms. Deadlocks stopped immediately after rolling out the index.
Key lesson
  • Never deploy DDL changes (schema, new queries) without reviewing the execution plan.
  • Missing indexes on UPDATE/DELETE WHERE clauses are a common root cause of deadlocks.
  • Use EXPLAIN ANALYZE before every new query in production-like data volumes.
Production debug guideIdentify and fix the top 5 production DB problems fast.4 entries
Symptom · 01
Query takes seconds to return when it used to be milliseconds
Fix
Check if a new index is needed or if the execution plan changed (parameter sniffing, stale statistics). Run EXPLAIN ANALYZE and look for seq scans on large tables.
Symptom · 02
Deadlock errors in application logs
Fix
Identify the deadlocked queries from the DB logs (pg_locks/innodb status). Ensure transactions access resources in the same order. Keep transactions short.
Symptom · 03
High CPU with low I/O — database is doing compute-heavy work
Fix
Look for queries with large in-memory sorts, hash joins, or missing indexes. Check for unoptimized aggregations or non-SARGable WHERE clauses.
Symptom · 04
Connection pool exhaustion — 'too many connections' errors
Fix
Find long-running or idle-in-transaction queries (pg_stat_activity / SHOW PROCESSLIST). Close stale connections. Increase pool size only as last resort.
★ Quick DB Debugging Cheat SheetFive-second commands for common database crisis.
Slow SELECT with many joins
Immediate action
Run EXPLAIN ANALYZE on the query
Commands
EXPLAIN ANALYZE SELECT ...;
SHOW INDEX FROM table_name;
Fix now
Add missing index on join columns, or rewrite join order using STRAIGHT_JOIN.
Deadlock detected+
Immediate action
Identify locking queries from system tables
Commands
SHOW ENGINE INNODB STATUS\G -- MySQL
SELECT * FROM pg_locks WHERE granted = false; -- PostgreSQL
Fix now
Kill the blocking transaction (CALL mysql.rds_kill(thread_id) or pg_terminate_backend(pid)), then add retry logic.
Transaction log full / WAL growing fast+
Immediate action
Check active transactions
Commands
SELECT * FROM pg_stat_activity WHERE state = 'idle in transaction';
CHECKPOINT; -- force flush
Fix now
Commit or rollback long-running idle transactions, then take a backup to reclaim log space.
FeatureClustered IndexNon-Clustered Index
Number per tableOnly 1Up to 999 (SQL Server) / many
Physical row orderRows ARE the index — physically sortedSeparate structure with row pointers
Read speedFastest for range scans on indexed columnFast for exact lookups; requires pointer follow
Write overheadModerate (row order must be maintained)Higher per index (each index updated separately)
StorageNo extra storage — index IS the tableExtra disk space per index
Default usageUsually the PRIMARY KEYForeign keys, WHERE/ORDER BY columns
Best forID-based range queries: WHERE id BETWEEN 100 AND 200Filtering on non-PK columns: WHERE email = '...'

Key takeaways

1
ACID isn't just a buzzword
each letter solves a specific real-world failure mode: power cuts (Durability), crashes mid-transaction (Atomicity), constraint violations (Consistency), and concurrent users corrupting shared data (Isolation).
2
Normalization to 3NF is correct for OLTP systems, but intentional denormalization is often the right call for OLAP/analytics
always tie your answer to the read/write profile of the system.
3
A clustered index physically reorders the table rows and you get exactly one per table; non-clustered indexes are separate pointer structures and you can have many
but every index adds write overhead.
4
Isolation levels are a dial between consistency and performance
READ COMMITTED is the pragmatic default for most apps, SERIALIZABLE is safest but slowest, and READ UNCOMMITTED is almost never appropriate in production code.
5
Execution plans reveal the truth about query performance
learn to read them before you ship any new query to production.

Common mistakes to avoid

4 patterns
×

Confusing DELETE, TRUNCATE and DROP

Symptom
Candidates say 'they all remove data' without knowing the crucial differences. DELETE is DML: removes rows one-by-one, fires triggers, can be rolled back. TRUNCATE is DDL: removes all rows instantly, resets identity counters, cannot be rolled back in most databases. DROP removes the entire table structure and data permanently.
Fix
Remember the mantra: DELETE removes rows carefully, TRUNCATE nukes the data but keeps the table, DROP destroys everything.
×

Thinking more indexes always means better performance

Symptom
Candidates index every column 'to be safe' and then wonder why their INSERT-heavy app slows to a crawl. Every index must be updated on every write. A table with 10 indexes on a write-heavy workload can be 10x slower on inserts than the same table with 1 index.
Fix
Only add indexes for columns that appear in your actual WHERE, JOIN ON, and ORDER BY clauses, and benchmark before and after.
×

Misdefining a transaction as 'a single SQL statement'

Symptom
This is wrong and interviewers know it. A transaction is a logical unit of work that can contain multiple statements, all of which succeed or fail together. A single statement can be its own transaction (auto-commit), but the defining characteristic is the ACID guarantee around a group of operations.
Fix
Define a transaction by its ACID properties, not by its size.
×

Assuming FOREIGN KEYs never hurt performance

Symptom
In high-throughput write systems, foreign key checks on every insert/update can cause contention, especially with cascading deletes.
Fix
Evaluate whether foreign keys are needed for data integrity or if application-level checks are sufficient for performance-critical paths.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
LeetCode Hard (SQL): Find the 'Top 3 Salaries' per Department using a wi...
Q02SENIOR
Scenario: Your production database is experiencing high CPU usage during...
Q03SENIOR
Tradeoff Analysis: If normalization is so great, why do large-scale anal...
Q04SENIOR
LeetCode Medium: Write a query to find all 'Customers who never ordered'...
Q01 of 04SENIOR

LeetCode Hard (SQL): Find the 'Top 3 Salaries' per Department using a window function. If two employees share the same salary, they should both be included in the ranking. (Testing: DENSE_RANK() vs RANK()).

ANSWER
Use DENSE_RANK() because it assigns the same rank to ties and does not skip numbers. RANK() would skip numbers after ties, breaking the 'top 3' requirement (e.g., if two are tied at rank 1, next rank would be 3, missing the third salary). Query: SELECT department_id, employee_id, salary FROM ( SELECT *, DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk FROM employees ) ranked WHERE rnk <= 3;
FAQ · 4 QUESTIONS

Frequently Asked Questions

01
What is the difference between a primary key and a unique key in SQL?
02
What is a deadlock in a database and how do you prevent it?
03
What is the difference between WHERE and HAVING in SQL?
04
How do you detect and resolve a phantom read problem?
🔥

That's DBMS. Mark it forged?

6 min read · try the examples if you haven't

Previous
ER Model in DBMS
10 / 11 · DBMS
Next
Checkpoint in DBMS