Skip to content
SQL & database handbook · PDF ebook

SQL and databases, from first query to sharding.

26 chapters that take you from SELECT and joins through window functions, indexing, EXPLAIN, transactions, isolation and MVCC, to replication and sharding. 14 classic problems, a question bank and a 7-day revision plan included.

26
chapters
6
parts
14
classic SQL problems
7
day revision plan
₹79₹19960% off
  • Secure checkout via Razorpay
  • Digital PDF ebook
  • Read on phone, tablet or laptop
SQL & Database Interview Handbook ebook coverPDF ebook
Quick answers

Short answers, straight from the book

The questions asked most in exams and interviews, answered the way you would say them out loud.

  • What is the difference between WHERE and HAVING?

    WHERE filters individual rows before they are grouped, so it cannot use aggregates. HAVING filters whole groups after GROUP BY, so it can, for example HAVING COUNT(*) >= 2.

  • ROW_NUMBER vs RANK vs DENSE_RANK?

    All three number rows in a window. ROW_NUMBER gives every row a unique number even on ties. RANK gives ties the same number and then skips (1, 2, 2, 4). DENSE_RANK gives ties the same number without gaps (1, 2, 2, 3), which is why it is used for the Nth highest salary.

  • Clustered vs non-clustered index?

    A clustered index stores the table rows themselves in index order, so a table has at most one. A non-clustered index is a separate structure of keys pointing back to the rows; a table can have many, and a query it fully covers can be answered from the index alone.

  • Which isolation level prevents which anomaly?

    READ COMMITTED prevents dirty reads. REPEATABLE READ also prevents non-repeatable reads. SERIALIZABLE prevents those plus phantoms and write skew. Higher levels are safer but block or abort more transactions.

Try it free

Three SQL labs, running on real rows

One tiny employees and departments dataset. Step through how a query really executes, flip between join types, and see exactly how ranking functions treat a tie.

The query, as written

SELECT dept_id, COUNT(*) AS headcount,       AVG(salary) AS avg_salaryFROM employeesWHERE salary >= 70000GROUP BY dept_idHAVING COUNT(*) >= 2ORDER BY avg_salary DESCLIMIT 1;

Written order starts with SELECT. The database runs it in a different order: step through it.

FROM. Start with every row of the table. Joins happen here too, before anything is filtered.

idnamedept_idsalary
1Asha11,90,000
2Ravi11,65,000
3Neha11,65,000
4Meera21,20,000
5Kabir295,000
6Isha370,000
7ArjunNULL60,000

Two tables

employees

  • Asha1
  • Ravi1
  • Neha1
  • Meera2
  • Kabir2
  • Isha3
  • ArjunNULL

departments

  • Engineering1
  • Sales2
  • Support3
  • Research4

Highlighted rows reach the result. Arjun has no department; Research has no employees.

SELECT e.name, d.name AS dept
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id;

7 rows. Every employee, matched or not. Arjun stays, with NULL for the department.

e.namedept
AshaEngineering
RaviEngineering
NehaEngineering
MeeraSales
KabirSales
IshaSupport
ArjunNULL

ROW_NUMBER vs RANK vs DENSE_RANK

SELECT name, dept_id, salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn,
  RANK()       OVER (ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY salary DESC) AS drnk,
  LAG(salary)  OVER (ORDER BY salary DESC) AS prev_salary
FROM employees;
namedeptsalaryrnrnkdrnkprev_salary
AshaEngineering1,90,000111NULL
RaviEngineering1,65,0002221,90,000
NehaEngineering1,65,0003221,65,000
MeeraSales1,20,0004431,65,000
KabirSales95,0005541,20,000
IshaSupport70,00066595,000
ArjunNULL60,00077670,000

Ravi and Neha tie at 1,65,000: ROW_NUMBER still splits them, RANK gives both 2 and skips to 4, DENSE_RANK gives both 2 and continues with 3. That is why the Nth-highest salary uses DENSE_RANK.

Isolation levelDirty readNon-repeatable readPhantom readNote
READ UNCOMMITTEDPossiblePossiblePossiblePostgreSQL treats it as READ COMMITTED
READ COMMITTEDPreventedPossiblePossibleDefault in PostgreSQL and Oracle
REPEATABLE READPreventedPreventedPossibleDefault in MySQL InnoDB; no phantoms in PostgreSQL
SERIALIZABLEPreventedPreventedPreventedSafest; may abort transactions that must retry
Mental models

Two paths explain most database interviews

One is how a single query runs. The other is the journey every growing product takes with its database.

Model 01

How a query runs

The database parses your SQL, the cost-based optimizer picks a plan, and the executor reads pages through the buffer pool, writing changes to the WAL first.

  1. 1Parse
  2. 2Optimize
  3. 3Execute
  4. 4Buffer pool
  5. 5WAL & disk

Most 'why is this slow' answers live in the optimize and execute steps: wrong plan, missing index or stale statistics. EXPLAIN ANALYZE shows both.

Model 02

From first query to scaled database

The book follows the same order: write correct queries, design the schema, make it fast, keep it correct under concurrency, survive failures, then scale out.

  1. 1Query
  2. 2Design
  3. 3Index
  4. 4Transact
  5. 5Recover
  6. 6Scale

Interviewers move along this path too. If you can explain each step's trade-off, you can follow any follow-up question.

Syllabus

26 chapters in 6 parts

SQL foundations, database design, storage and indexing, transactions and recovery, scaling and distributed databases, then security, a question bank and cheat sheets.

27 chapters · 187 sections

Part ISQL FoundationsFrom keys and constraints to joins, CTEs, window functions and the 14 problems interviewers keep asking.
00How to Use This Book4 sections
  • What this handbook covers
  • How every chapter is built
  • Suggested study paths
  • Run the examples yourself
01Database Fundamentals6 sections
  • What is a database and a DBMS?
  • Keys: the glue of the relational model
  • Constraints: let the database defend your data
  • Data types you must know
  • SQL is a family of sub-languages
  • The sample database used in every chapter
02SELECT Essentials6 sections
  • Execution order: the mental model behind every query
  • Filtering with WHERE
  • NULL: the value that is not a value
  • Sorting, limiting and removing duplicates
  • Aggregation and GROUP BY
  • CASE, COALESCE and common functions
03Joins10 sections
  • Why joins exist
  • INNER JOIN
  • LEFT JOIN: keep everything from the left
  • RIGHT and FULL OUTER JOIN
  • Anti-join: find rows with NO match
  • Self join: employees and their managers
  • CROSS JOIN
  • Joining three or more tables
  • Join traps interviewers love
  • How databases execute joins (preview)
04Subqueries, CTEs and Set Operations6 sections
  • Subquery types
  • EXISTS vs IN, and the NOT IN trap
  • Common Table Expressions (WITH)
  • Recursive CTE: walking hierarchies
  • Set operations
  • LATERAL: a subquery that can see the row to its left
05Window Functions6 sections
  • The idea
  • Ranking: ROW_NUMBER vs RANK vs DENSE_RANK
  • Top-N per group
  • LAG and LEAD: compare with the previous / next row
  • Running totals and moving averages
  • Per-group comparison and share of total
06Classic SQL Interview Problems14 sections
  • Second highest salary (without LIMIT tricks)
  • Nth highest salary per department
  • Find duplicate rows
  • Delete duplicates, keeping one row
  • Employees earning more than their manager
  • Department with the highest average salary
  • Departments with no employees
  • Top 3 salaries in each department
  • Consecutive days: gaps and islands
  • Running total per customer
  • Month-over-month growth
  • Median salary
  • Pivot with conditional aggregation
  • Customers whose total spend exceeds the average customer spend
07DDL, DML and Database Programmability7 sections
  • INSERT, UPDATE, DELETE and RETURNING
  • UPSERT: insert or update in one atomic statement
  • DELETE vs TRUNCATE vs DROP
  • ALTER TABLE safely
  • Views and materialized views
  • Functions, stored procedures and triggers
  • Temporary tables, sequences and identity
Part IIDatabase DesignNormalize with intent, denormalize on purpose, and model real systems such as multi-tenant SaaS.
08Normalization9 sections
  • Why normalize? The three anomalies
  • Functional dependencies: the vocabulary
  • First Normal Form (1NF): atomic values, no repeating groups
  • Second Normal Form (2NF): no partial dependencies
  • Third Normal Form (3NF): no transitive dependencies
  • Boyce-Codd Normal Form (BCNF)
  • Higher forms in one minute
  • Normalization at a glance
  • Denormalization: breaking the rules on purpose
09Schema Design and Data Modeling7 sections
  • Relationships and how to implement them
  • Choosing a primary key
  • Standard columns worth adding
  • Keeping history: Slowly Changing Dimension Type 2
  • Multi-tenant designs (SaaS)
  • Anti-patterns to avoid
  • Mini design walk-through: URL shortener
Part IIIStorage, Indexing and PerformanceSee how rows become bytes, why an index helps or is ignored, and how to read EXPLAIN like a pro.
10Storage Internals and Paging5 sections
  • From table to bytes
  • Where is my row? The ctid
  • The buffer pool: RAM in front of disk
  • What happens on UPDATE and DELETE (PostgreSQL)
  • Paging through results (pagination)
11Indexing in Depth10 sections
  • The problem indexes solve
  • B+ tree: the default index
  • Clustered vs non-clustered
  • See an index change a query plan
  • Composite indexes and the leftmost-prefix rule
  • Covering indexes and index-only scans
  • Partial and expression indexes
  • Why my index is NOT used
  • Index types beyond B-tree
  • The cost of indexes
12Query Execution and Optimization7 sections
  • The optimizer is cost-based
  • Reading EXPLAIN
  • Scan types
  • Join algorithms in action
  • Statistics and misestimates
  • The tuning checklist
  • Common anti-patterns
Part IVTransactions, Concurrency and Failure RecoveryACID, isolation anomalies with live demos, MVCC, locking, deadlocks, WAL and crash recovery.
13Transactions and ACID6 sections
  • Why transactions exist
  • BEGIN, COMMIT and ROLLBACK
  • Autocommit
  • Savepoints: partial rollback
  • Transactions in application code
  • Transaction best practices
14Isolation Levels and Concurrency Anomalies8 sections
  • The problem: concurrency
  • The anomalies
  • The four standard isolation levels
  • Demo 1: non-repeatable read at READ COMMITTED
  • Demo 2: REPEATABLE READ keeps a stable snapshot (and no phantoms in PostgreSQL)
  • Demo 3: lost update
  • Demo 4: write skew: snapshot isolation is not serializable
  • Setting the isolation level
15Locking, MVCC and Deadlocks8 sections
  • Two ways to isolate: locks and versions
  • MVCC: how PostgreSQL keeps versions
  • Lock modes
  • Pessimistic locking: SELECT ... FOR UPDATE
  • Optimistic locking: detect conflicts instead of preventing them
  • Deadlocks
  • Finding blockers in production
  • Other lock concepts to mention
16Durability, WAL, Failures and Recovery5 sections
  • The durability problem
  • Crash recovery: a real experiment
  • What can fail? A failure catalogue
  • Backups: the last line of defence
  • RPO and RTO
Part VScaling and Distributed DatabasesReplication, partitioning, sharding, caching and distributed consistency, explained as an interview roadmap.
17Scaling Databases: The Roadmap4 sections
  • Scaling is about bottlenecks
  • Vertical vs horizontal scaling
  • Read-heavy vs write-heavy
  • Back-of-envelope numbers worth knowing
18Replication and High Availability9 sections
  • What replication does
  • Real experiment: a streaming replica
  • Synchronous vs asynchronous replication
  • Replication lag and its anomalies
  • Physical vs logical replication
  • Failover and split brain
  • Consensus in one paragraph
  • Leaderless quorums
  • HA checklist for an interview answer
19Partitioning5 sections
  • What and why
  • Hands-on: monthly range partitions
  • Rules and gotchas
  • Horizontal vs vertical partitioning
  • Partitioning vs sharding
20Sharding8 sections
  • What is sharding?
  • Choosing the shard key (the most important decision)
  • Strategies compared
  • Consistent hashing, proven in code
  • Global unique IDs across shards
  • What sharding breaks (and the workarounds)
  • Resharding without downtime
  • When NOT to shard
21Caching and Connection Pooling3 sections
  • Why a cache
  • Hard problems
  • Connection pooling
22Distributed Transactions and Consistency7 sections
  • CAP theorem
  • Consistency models, strongest to weakest
  • ACID vs BASE
  • Two-Phase Commit (2PC)
  • Saga: a sequence of local transactions with compensations
  • The transactional outbox
  • Idempotency: making retries safe
23SQL vs NoSQL, OLTP vs OLAP and NewSQL4 sections
  • SQL vs NoSQL
  • OLTP vs OLAP
  • NewSQL and distributed SQL
  • Quick decision guide
Part VISecurity, Interview Bank and Cheat SheetsLock the database down, drill the full question bank and finish with a 7-day revision plan.
24Database Security4 sections
  • SQL injection
  • Authentication, roles and least privilege
  • Row-Level Security (RLS)
  • Protecting data at rest and in transit
25Interview Question Bank8 sections
  • A. SQL and database basics
  • B. Querying
  • C. Design and normalization
  • D. Indexing and performance
  • E. Transactions and concurrency
  • F. Durability, failures and recovery
  • G. Scaling and distributed databases
  • H. Eight scenario questions
26Cheat Sheets and 7-Day Revision Plan11 sections
  • SQL syntax cheat sheet
  • Window function cheat sheet
  • Isolation levels at a glance
  • Index cheat sheet
  • Error codes worth recognising (PostgreSQL SQLSTATE)
  • PostgreSQL vs MySQL (InnoDB): talking points
  • Failure and scaling quick reference
  • 7-day revision plan
  • Interview-day checklist
  • Glossary
  • Final words
Free samples

Six interview problems, solved

Straight from the book: the query, the output and the one line to say in the interview.

Second highest salary, without LIMIT tricks

The most asked SQL question. Show two tie-safe answers: a subquery on MAX, and DENSE_RANK that generalises to the Nth highest. Tip: Use DENSE_RANK, not ROW_NUMBER: duplicates of the top salary must not hide the second one.

second_highest.sql
-- 1) Subquery on MAX: returns NULL if no 2nd value
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- 2) DENSE_RANK: change 2 to N for the Nth highest
SELECT DISTINCT salary
FROM (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 2;

-- Output
--  second_highest
-- ----------------
--          165000
Choose your book

The CS core set: Networks, OS and SQL

The three subjects asked in almost every campus and off-campus technical round. Start with this one, add the others when you need them.

Computer Networks

Computer Network

OSI and TCP/IP, subnetting, routing, TCP, DNS, HTTP and TLS, with solved numericals.

  • 12 chapters, physical to application
  • 25 solved numericals
  • Interview Q&A and port cheat-sheet
₹79₹19960% off
Details
Operating Systems

Operating Systems

Processes, threads, scheduling, synchronization, deadlocks, memory and file systems.

  • Scheduling with Gantt charts
  • Paging, page replacement, deadlocks
  • Interview Q&A and numericals
₹79₹19960% off
Details
This page
SQL & Databases

SQL & Database Interview Handbook

From first SELECT to window functions, indexes, transactions and scaling databases.

  • Joins, CTEs, window functions
  • Indexes, transactions, isolation
  • Interview-style query problems
₹79₹19960% off
Who it's for

Made for SQL and database rounds at product companies

  • Backend and full-stack engineers

    Go past CRUD: indexing, EXPLAIN, transactions, isolation, locking and the scaling questions asked in senior rounds.

    • Indexes and EXPLAIN
    • Isolation and MVCC
    • Replication and sharding
  • Data and analytics candidates

    Window functions, CTEs, gaps and islands, pivots and the 14 classic problems that show up in SQL screens.

    • Window functions
    • 14 classic problems
    • Pivots and CTEs
  • Freshers and students

    Starts from keys and constraints and builds up, so DBMS theory and practical SQL are covered in one place.

    • Normal forms
    • ACID
    • 7-day plan

What you get

  • 26 chapters in 6 parts

    One path from SELECT to distributed databases.

  • Run every example

    One sample database across chapters, so every query and plan reproduces.

  • Real experiments

    Crash recovery, a streaming replica, partitions and four isolation demos.

  • 14 classic SQL problems

    Nth salary, duplicates, top-N per group, gaps and islands, median.

  • Interview question bank

    Eight sections plus eight scenario questions.

  • Cheat sheets and a 7-day plan

    SQL, windows, isolation, indexes and an interview-day checklist.

₹79₹19960% off
Questions

Before you buy

Anything else? Write to [email protected]

What is the SQL & Database Interview Handbook?

It is a Target Trek ebook of 26 chapters in 6 parts that takes you from SQL basics to database internals and distributed systems. It covers SQL queries, joins, window functions, schema design, indexing, query optimization, transactions, isolation levels, MVCC, locking, replication, sharding, security and a full interview question bank.

Which SQL topics does the book cover?

SELECT and execution order, NULL handling, aggregation, all join types including anti-joins and self joins, subqueries, EXISTS vs IN, CTEs, recursive CTEs, LATERAL, set operations, window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, running totals), DDL, DML, UPSERT, views, stored procedures and triggers.

Does it include classic SQL interview problems?

Yes. Chapter 6 solves 14 classic problems: second and Nth highest salary, finding and deleting duplicates, top 3 salaries per department, gaps and islands, running totals, month-over-month growth, median salary, pivots with conditional aggregation and customers spending above average.

Does the book explain indexing and query optimization?

Yes. It covers B+ trees, clustered vs non-clustered indexes, composite indexes and the leftmost-prefix rule, covering indexes, partial and expression indexes, why an index is not used, index types beyond B-tree, reading EXPLAIN, scan types, join algorithms, statistics and a tuning checklist.

Are transactions, isolation levels and locking covered?

Yes. Part IV explains ACID, savepoints, the four standard isolation levels, and runs four live demos: non-repeatable read, stable snapshots, lost update and write skew. It also covers MVCC, lock modes, SELECT ... FOR UPDATE, optimistic locking, deadlocks and WAL-based crash recovery.

Does it cover scaling, replication and sharding?

Yes. Part V covers vertical vs horizontal scaling, replication and high availability, failover and split brain, partitioning, choosing a shard key, consistent hashing, resharding, caching, connection pooling, CAP theorem, two-phase commit, sagas, the transactional outbox and idempotency.

Is the book based on PostgreSQL or MySQL?

Examples and experiments use PostgreSQL, and the book includes a PostgreSQL vs MySQL (InnoDB) chapter section with interview talking points. Core SQL and concepts apply to any relational database.

Who is this book for?

Backend developers, full-stack engineers, data and analytics candidates, and anyone preparing for SQL or database rounds at product companies. It works for beginners starting from keys and constraints and for experienced engineers revising internals and scaling.

How long does it take to prepare with this book?

The final chapter includes a 7-day revision plan, an interview-day checklist and cheat sheets for SQL syntax, window functions, isolation levels and indexes, so you can structure your preparation in a week.

How does checkout work and what format is it?

It is a digital ebook with instant access after checkout, and payment opens in a secure checkout window. Digital products are non-refundable after purchase. For help write to [email protected].

Walk into the SQL round knowing why, not just how.

26 chapters, 14 classic problems and a 7-day revision plan, in one PDF you can read anywhere.

₹79₹19960% off
Resume Lab by Target Trek

Applying everywhere but getting no interview calls?

Your book gets you ready for the interview. A better resume gets you the call. See exactly which lines cost you shortlists, and how to fix each one.

~2 min
AI report
Real people
review it
Pay once
no subscription
SQL & Database Interview Handbook
₹79₹19960% off