Database NotesRohit’s interview study guide
Practice

All questions

Every interview answer and quiz card in Database, in one place: 219 interview answers and 181 quiz cards from 27 chapters. Try each one out loud before you open its answer; “Open in topic” takes you to the full explanation.

What is a database, and why not just use files?

Show answer

"A database is an organised collection of data, and the DBMS is the software that manages it. I'd use one instead of files because it solves the hard problems once: concurrent access without lost updates, durability through a write-ahead log so a crash doesn't corrupt anything, integrity rules like unique and foreign keys that every client has to obey, transactions so related changes happen all or nothing, and a declarative query language with an optimizer and indexes, so I describe the result and the engine finds an efficient way to get it."

Open in topic →

Which delete succeeds?

Zara (6) has never ordered; Noah (5) has one order. Inside a transaction (rolled back afterwards), what happens to each DELETE?

SQL
START TRANSACTION;
DELETE FROM customers WHERE id = 6;
DELETE FROM customers WHERE id = 5;
ROLLBACK;
Show answer

The first succeeds, the second fails:

Result
Query OK, 0 rows affected (0.000 sec)

Query OK, 1 row affected (0.000 sec)

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`shop`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`))

Query OK, 0 rows affected (0.006 sec)
What’s happening
  1. The foreign key orders.customer_id → customers.id only protects customers that are referenced. No order points at Zara, so deleting her leaves nothing orphaned and it's allowed.
  2. Order 7 points at Noah. Deleting him would leave order 7 referring to a customer that doesn't exist, so InnoDB rejects it with 1451. The constraint is checked per row, at the moment of the change.
  3. The default referential action is RESTRICT (MySQL also calls it NO ACTION; InnoDB treats them the same). ON DELETE CASCADE would delete order 7 too, and SET NULL would need a nullable customer_id.
  4. The START TRANSACTION and ROLLBACK around them matter when you type this: the ROLLBACK puts Zara back, so your shop still has six customers and every later result still matches the page. Leave them out and Zara is gone for good (reload shop.sql to get her back; the commands are in "Reset, stop and remove" under Set up your own playground).
Open in topic →

What's the difference between a primary key and a foreign key?

Show answer

"A primary key uniquely identifies each row in its own table. It can't be NULL, there's one per table, and in InnoDB the table is physically stored in primary-key order. A foreign key is a column in another table that holds those key values to link the two, like orders.customer_id pointing at customers.id. The database enforces it: you can't insert an order for a customer that doesn't exist, and you can't delete a customer who still has orders unless you've declared a referential action like CASCADE or SET NULL."

Open in topic →

What does this return?

SQL
SELECT 5 --1;
Show answer

It returns 6.

What’s happening
  1. In MySQL, -- starts a comment only when it is followed by a space (or a control character). --1 has no space.
  2. So the parser reads 5 - -1: five minus negative one.
  3. 5 - (-1) = 6, and the column is named after the expression text, 5 --1.
  4. Write SELECT 5 -- 1 (with a space) and the comment starts, the query is just SELECT 5, and you get 5. MySQL also accepts # to end of line and /* … */ comments. I ran both versions on 9.7 to confirm.
Open in topic →

What are DDL, DML, DCL and TCL?

Show answer

"They're the families of SQL statements. DDL defines structure: CREATE, ALTER, DROP, TRUNCATE. DML changes data: INSERT, UPDATE, DELETE. SELECT is sometimes split out as DQL. DCL is permissions: GRANT and REVOKE. TCL controls transactions: BEGIN, COMMIT, ROLLBACK, SAVEPOINT. One MySQL detail worth knowing is that DDL causes an implicit commit, so you can't roll back a CREATE or ALTER, and TRUNCATE counts as DDL, which is one reason it can't be rolled back while DELETE can."

Open in topic →

When would you choose SQL over NoSQL?

Show answer

"I'd default to a relational database when the data is related and I need consistency: orders, payments, inventory, anything where foreign keys and multi-row transactions protect me, or where I don't know all the questions yet, because SQL can join and aggregate any way later. I'd pick a document store when data is naturally read and written as one aggregate, like a product catalogue with varied attributes, and when I need built-in horizontal scaling. A key-value store like Redis is for caching, sessions and counters. In practice many systems use more than one."

Open in topic →

Explain MySQL's architecture.

Show answer

"MySQL has a server layer and pluggable storage engines. The server layer handles connections and authentication, parses the SQL, and the optimizer chooses a plan, like which indexes to use and the join order, using statistics from the engine. The executor then calls the storage engine API to read and write rows. The default engine is InnoDB: it keeps pages in a buffer pool, writes changes to a redo log before commit for crash safety, keeps undo records for rollback and MVCC, uses row-level locking, and stores each table as a B+tree clustered on the primary key. MyISAM is the old engine without transactions or crash recovery."

Open in topic →

Which MySQL version would you run in production today?

Show answer

"An LTS release: MySQL 9.7 LTS for new systems, or 8.4 LTS if the platform or tooling isn't ready yet. LTS releases freeze features and only take fixes, so upgrades within the series are low risk, and they get five years of premier support. Innovation releases, now numbered by year and month like 26.7, are for trying new features, and each is supported only until the next one. 8.0 reached end of life in April 2026 and 5.7 in 2023, so anything on those should be planned onto 8.4 and then 9.7, because you can't skip an LTS."

Open in topic →

How does an application connect to MySQL safely?

Show answer

"Through a driver like mysql2 using a connection pool, so connections are reused instead of opened per request. I'd give the app its own account with only the privileges it needs, not root, keep the password in configuration or a secrets manager, use TLS, which MySQL 8 and later enables by default over TCP, and always pass values as placeholders in prepared statements so user input can never change the SQL."

Open in topic →

Read the data: who isn't in Engineering?

Using only the data below (or your memory of the quirks), how many rows does this return?

SQL
SELECT COUNT(*) AS not_engineering FROM employees WHERE department_id <> 1;
Show answer

5, not 6:

Result
+-----------------+
| not_engineering |
+-----------------+
|               5 |
+-----------------+
What’s happening
  1. Ten employees, four of them in Engineering (Asha, Ben, Chloe, Dev). That leaves six people who are "not in Engineering".
  2. But Jonas's department_id is NULL, and NULL <> 1 is unknown, not true, so WHERE drops him.
  3. The query counts Sales (3) and Support (2): 5. To include Jonas, add OR department_id IS NULL. This is the sample data's most important quirk; NULL and three-valued logic explains the rule.
Open in topic →

What does SELECT return?

Show answer

"A result set, which is itself a table: rows and named columns. FROM is evaluated first and supplies the rows, WHERE filters them, and SELECT decides which columns or expressions come back. Without ORDER BY the row order is undefined. In application code I list the columns explicitly instead of SELECT star, so schema changes don't silently change what's returned and the optimizer can use covering indexes."

Open in topic →

Spot the bug: laptops and phones under 1000

The goal is "laptops (category 2) or phones (category 3) that cost under 1000". What does this return?

SQL
SELECT id, name, category_id, price FROM products
WHERE category_id = 2 OR category_id = 3 AND price < 1000;
Show answer

It returns three rows, including the 1299 MacBook Air:

Result
+----+--------------+-------------+---------+
| id | name         | category_id | price   |
+----+--------------+-------------+---------+
|  1 | ThinkBook 14 |           2 |  899.00 |
|  2 | MacBook Air  |           2 | 1299.00 |
|  3 | Pixel 10     |           3 |  799.00 |
+----+--------------+-------------+---------+
What’s happening
  1. AND binds tighter than OR, just as * binds tighter than +. So the condition is read as category_id = 2 OR (category_id = 3 AND price < 1000).
  2. Every laptop passes the first half on its own, so the MacBook Air (category 2, 1299) is in, whatever its price.
  3. Phones must also be under 1000: the Pixel (799) is in, the iPhone (1099) is out.
  4. The fix is parentheses: WHERE (category_id = 2 OR category_id = 3) AND price < 1000, which returns only the ThinkBook and the Pixel. Or use category_id IN (2, 3) AND price < 1000, which can't be misread.
Open in topic →

What's the difference between WHERE and HAVING?

Show answer

"WHERE filters individual rows before grouping, so it can't use aggregate functions. HAVING filters groups after GROUP BY, so it's where conditions like COUNT(*) > 5 go. If a condition doesn't involve an aggregate, put it in WHERE: rows thrown away early never have to be grouped, and WHERE can use indexes."

Open in topic →

NOT IN and a NULL

"Which employees manage nobody?" What does this return?

SQL
SELECT name FROM employees
WHERE id NOT IN (SELECT manager_id FROM employees);
Show answer

Nothing: Empty set. The six people who manage nobody (Chloe, Dev, Farid, Grace, Isla, Jonas) are all missing.

What’s happening
  1. The subquery returns every manager_id, and Asha's is NULL because she has no manager. So the list is (NULL, 1, 1, 2, 1, 5, 5, 1, 8, 1).
  2. id NOT IN (list) means id <> NULL AND id <> 1 AND id <> 2 AND …. For Chloe (id 3) every comparison with a real number is true, but 3 <> NULL is UNKNOWN.
  3. TRUE AND … AND UNKNOWN is UNKNOWN, so WHERE drops Chloe. The same happens to every row: one NULL in a NOT IN list makes the whole test unknown for every row.
  4. Fix it by filtering the NULL out (WHERE manager_id IS NOT NULL inside the subquery) or, better, use NOT EXISTS (SELECT 1 FROM employees r WHERE r.manager_id = e.id), which isn't affected by NULLs. Both return the six names; I ran both. NOT IN (1, 2, NULL) with a literal list has the same problem.
Open in topic →

Why does WHERE column = NULL return nothing?

Show answer

"Because NULL means unknown, and any comparison with an unknown is itself unknown, not true. SQL uses three-valued logic and WHERE only keeps rows where the condition is true, so = NULL matches nothing, not even the NULL rows. You test with IS NULL or IS NOT NULL, or in MySQL the null-safe operator <=>. The same logic is why NOT IN with a subquery that returns a NULL gives an empty result, so I use NOT EXISTS for anti-joins."

Open in topic →

Why is "pending" first?

SQL
SELECT id, status FROM orders ORDER BY status;

The statuses are pending, paid, shipped and cancelled. Alphabetically cancelled would come first. What comes first here?

Show answer

pending, then paid, shipped, and cancelled last:

Result
+----+-----------+
| id | status    |
+----+-----------+
|  6 | pending   |
|  2 | paid      |
|  7 | paid      |
|  1 | shipped   |
|  3 | shipped   |
|  5 | shipped   |
|  8 | shipped   |
|  4 | cancelled |
+----+-----------+
What’s happening
  1. status is an ENUM('pending','paid','shipped','cancelled'). Internally MySQL stores each value as its position in the list: pending = 1, paid = 2, shipped = 3, cancelled = 4.
  2. ORDER BY status sorts by those numbers, not by the text. That's why the order matches the ENUM definition.
  3. To sort alphabetically, sort the text: ORDER BY CAST(status AS CHAR) returns cancelled, paid, paid, pending, shipped… (I ran it). To sort in a business order of your own choosing, use a CASE expression (see CASE expressions).
  4. This is one of several ENUM surprises; ENUM, SET and BOOLEAN has the rest.
Open in topic →

Is the order of rows guaranteed without ORDER BY?

Show answer

"No. A table is a set, so without ORDER BY the database returns rows in whatever order the chosen plan produces: primary-key order for a table scan in InnoDB, index order if it used an index, arbitrary after a hash join or a parallel read. That can change when data grows, an index is added or the version changes. MySQL 8.0 even stopped GROUP BY sorting implicitly, which broke code that relied on it. If order matters, I write ORDER BY, with a unique tiebreaker if I'm paginating."

Open in topic →

Second-highest salary

A classic. What do these return?

SQL
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
Show answer

The first returns Chloe, 142000.00; the second returns 130000.00.

Result
+-------+-----------+
| name  | salary    |
+-------+-----------+
| Chloe | 142000.00 |
+-------+-----------+
+-----------+
| salary    |
+-----------+
| 130000.00 |
+-----------+
What’s happening
  1. Sorted by salary, the rows are Asha 185000, Ben 142000, Chloe 142000, Elena 130000, … Skipping two rows lands on Chloe, so the first query says the "third-highest salary" is 142000, which is really the second-highest again. (Whether Ben or Chloe is second is itself undefined.)
  2. DISTINCT removes duplicate salaries before ORDER BY and LIMIT: the distinct list is 185000, 142000, 130000, … Skipping two gives 130000, the true third-highest salary.
  3. Which one is right depends on the question: "the third-highest-paid person" or "the third-highest salary". Interviewers ask this to see whether you notice ties.
  4. DENSE_RANK() handles it more clearly and extends to "per department"; see ROW_NUMBER, RANK and DENSE_RANK.
Open in topic →

How do you paginate in MySQL, and what's the problem with OFFSET?

Show answer

"With ORDER BY on a unique key plus LIMIT and OFFSET, for example ORDER BY created_at, id LIMIT 20 OFFSET 40. The order has to be deterministic, otherwise rows can repeat or vanish between pages. The problem with OFFSET is cost: the server still reads and discards every skipped row, so deep pages get slower linearly, and rows inserted meanwhile shift the pages. For large tables I use keyset pagination: remember the last row's sort key and ask for WHERE (created_at, id) > (last_created_at, last_id) ORDER BY created_at, id LIMIT 20, which an index answers directly."

Open in topic →

What's the difference between DISTINCT and GROUP BY?

Show answer

"DISTINCT removes duplicate rows from the result, comparing all selected columns. GROUP BY collapses rows into groups so you can compute aggregates per group. For a plain list of unique values they give the same result and often the same plan. I reach for GROUP BY when I need counts or sums, and I treat a DISTINCT that's hiding join duplicates as a sign the query should use EXISTS instead."

Open in topic →

A missing comma

SQL
SELECT name price FROM products WHERE id = 1;

How many columns come back, and what are they called?

Show answer

One column, called price, containing the product name:

Result
+--------------+
| price        |
+--------------+
| ThinkBook 14 |
+--------------+
What’s happening
  1. Without a comma, name price isn't two columns. It's the column name followed by an alias, because AS is optional.
  2. So MySQL returns name and calls it price. No error, no warning.
  3. Code that reads row.price now gets 'ThinkBook 14'. Always writing AS for aliases makes this mistake stand out in review.
Open in topic →

Why can't you use a column alias in the WHERE clause?

Show answer

"Because WHERE is logically evaluated before the SELECT list. The query is processed FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY and LIMIT, so when WHERE runs the alias hasn't been defined yet. ORDER BY comes after SELECT, so aliases work there. The fixes are to repeat the expression in WHERE or to compute it in a derived table or CTE and filter in the outer query. MySQL also accepts aliases in GROUP BY and HAVING, which is an extension to the standard."

Open in topic →

First match wins

SQL
SELECT name, price,
       CASE WHEN price > 100  THEN 'over 100'
            WHEN price > 1000 THEN 'over 1000'
       END AS band
FROM products WHERE id IN (2, 7);

What's the MacBook Air's band (price 1299), and the charger's (29)?

Show answer

MacBook Air is over 100, and the charger is NULL.

Result
+---------------+---------+----------+
| name          | price   | band     |
+---------------+---------+----------+
| MacBook Air   | 1299.00 | over 100 |
| USB-C Charger |   29.00 | NULL     |
+---------------+---------+----------+
What’s happening
  1. For the MacBook, the first test 1299 > 100 is already true, so CASE stops there. The > 1000 branch can never be reached by anything, because anything over 1000 is also over 100.
  2. The charger fails both tests, and with no ELSE the result is NULL.
  3. Put the most specific (narrowest) condition first: WHEN price > 1000 before WHEN price > 100.
Open in topic →

How would you bucket values, or sort in a custom order, in SQL?

Show answer

"With a CASE expression. The searched form, CASE WHEN condition THEN value, checks conditions top to bottom and returns the first match, so I order the WHENs from most to least specific and always include an ELSE, otherwise unmatched rows become NULL. Because CASE is an expression, the same trick works in ORDER BY for a custom sort order, and inside SUM or COUNT for conditional aggregation, like SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END)."

Open in topic →

What do these return?

SQL
SELECT '5' + 3 AS str_plus, CONCAT(5, 3) AS concat_num, '5' || '3' AS pipes;
Show answer

8, 53 and 1, plus a warning:

Result
+----------+------------+-------+
| str_plus | concat_num | pipes |
+----------+------------+-------+
|        8 | 53         |     1 |
+----------+------------+-------+
1 row in set, 1 warning (0.000 sec)
What’s happening
  1. + is always arithmetic in MySQL, never concatenation, so the string '5' is converted to the number 5 and 5 + 3 = 8.
  2. CONCAT always produces a string, converting numbers to text: '5' and '3' join to '53' (shown left-aligned, as text).
  3. || in MySQL is logical OR by default, not concatenation as in standard SQL, PostgreSQL and Oracle. '5' and '3' are both non-zero, so '5' OR '3' is 1.
  4. The warning is 1287 '|| as a synonym for OR' is deprecated and will be removed in a future release. Please use OR instead. The PIPES_AS_CONCAT SQL mode switches || to concatenation; otherwise use CONCAT.
Open in topic →

How do you work with dates efficiently in SQL?

Show answer

"Store them in DATE, DATETIME or TIMESTAMP columns, never strings, and filter with half-open ranges on the raw column, like ordered_at >= '2025-01-01' AND ordered_at < '2026-01-01', so an index on the column can be used and the whole last day is included. Wrapping the column in YEAR() or DATE() in the WHERE clause forces a full scan. For differences I use TIMESTAMPDIFF, which counts complete units, and DATE_ADD with INTERVAL for arithmetic, which handles month ends."

Open in topic →

Where does a window function fit?

Window functions such as ROW_NUMBER() OVER (ORDER BY salary DESC) are computed in step 5, with SELECT. Can you filter on one in WHERE?

Show answer

No. WHERE runs at step 2, before any window function has been computed, so MySQL rejects it:

Result
ERROR 3593 (HY000): You cannot use the window function 'row_number' in this context.'

(The stray quote at the end is really in MySQL 9.7's message.) Compute it in a CTE or derived table and filter in the outer query.

What’s happening
  1. Window functions need the final set of rows that FROM, WHERE, GROUP BY and HAVING produce: a row's rank depends on which other rows survived.
  2. So they are evaluated in step 5, after HAVING. WHERE and HAVING can't see them.
  3. The standard pattern: WITH ranked AS (SELECT …, ROW_NUMBER() OVER (…) AS rn FROM …) SELECT … FROM ranked WHERE rn <= 3. See Top N per group.
Open in topic →

In what order does SQL evaluate a SELECT query?

Show answer

"Logically it's FROM and the joins first, then WHERE filters rows, GROUP BY forms groups, HAVING filters groups, then SELECT computes the output columns, including window functions, then DISTINCT, ORDER BY and finally LIMIT. That explains why you can't use a SELECT alias or an aggregate in WHERE, why aggregate conditions go in HAVING, and why ORDER BY can use aliases. The optimizer can physically reorder things, for example push filters into joins, but only if the result is the same as this logical order."

Open in topic →

Why do we need joins?

Show answer

"Because a normalised schema stores each fact once, in the table it belongs to, and links tables with keys. That avoids duplicated data and update anomalies, but it means most questions need data from several tables. A join recombines them at query time by matching rows on a condition, usually a foreign key equal to a primary key. Logically it's the Cartesian product filtered by the join condition; physically the optimizer uses indexes or hash tables so it never builds all those combinations."

Open in topic →

What does an INNER JOIN return?

Show answer

"Every combination of rows from the two tables where the ON condition is true. Rows without a match on the other side are dropped, and a row that matches several rows appears once per match, so joining customers to orders gives one row per order and customers without orders disappear. If I need those unmatched rows, I use a LEFT JOIN instead."

Open in topic →

Orders per customer, including zero

SQL
SELECT c.name, COUNT(*) AS count_star, COUNT(o.id) AS count_orders
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;

What are Zara's two counts?

Show answer

count_star is 1 and count_orders is 0:

Result
+-------+------------+--------------+
| name  | count_star | count_orders |
+-------+------------+--------------+
| Rohit |          2 |            2 |
| Maya  |          2 |            2 |
| Liam  |          2 |            2 |
| Sofia |          1 |            1 |
| Noah  |          1 |            1 |
| Zara  |          1 |            0 |
+-------+------------+--------------+
What’s happening
  1. The left join gives Zara one row, with o.id set to NULL.
  2. COUNT(*) counts rows, and she has one, so it says she has 1 order. That's wrong.
  3. COUNT(o.id) counts non-NULL values of o.id. Her only value is the join-produced NULL, so it's 0. That's right.
  4. Rule: after a left join, count a column from the right table, ideally its primary key. This is one of the most common reporting bugs.
Open in topic →

What's the difference between INNER JOIN and LEFT JOIN?

Show answer

"An inner join returns only rows that have a match in both tables. A left join returns every row from the left table, and where there's no match the right table's columns come back as NULL. So customers inner join orders drops customers who never ordered; customers left join orders keeps them with NULL order columns. Two follow-ups matter: count a right-table column, not star, after a left join, and put filters on the right table in the ON clause, because a WHERE on those columns turns the left join back into an inner join."

Open in topic →

Why the UNION version can lose rows

Now show each department's salaries, with the same emulation. How many rows should there be, and how many does UNION return?

SQL
SELECT d.name AS department, e.salary
FROM departments d LEFT JOIN employees e ON e.department_id = d.id
UNION
SELECT d.name, e.salary
FROM departments d RIGHT JOIN employees e ON e.department_id = d.id
ORDER BY department IS NULL, department, salary DESC;
Show answer

A real full join has 11 rows (10 employees plus Research). The UNION version returns 10:

Result
+-------------+-----------+
| department  | salary    |
+-------------+-----------+
| Engineering | 185000.00 |
| Engineering | 142000.00 |
| Engineering | 118000.00 |
| Research    |      NULL |
| Sales       | 130000.00 |
| Sales       |  99000.00 |
| Sales       |  95000.00 |
| Support     |  88000.00 |
| Support     |  72000.00 |
| NULL        |  91000.00 |
+-------------+-----------+
What’s happening
  1. Ben and Chloe are both in Engineering on 142000.00, so they produce two identical rows (Engineering, 142000.00). Without names, nothing tells them apart.
  2. UNION removes duplicates across the whole result, not just the overlap between the halves, so one of them disappears.
  3. The safe emulation keeps the left join whole and adds only the unmatched right rows, with UNION ALL (no de-duplication):
  4. … LEFT JOIN … UNION ALL SELECT d.name, e.salary FROM departments d RIGHT JOIN employees e ON e.department_id = d.id WHERE d.id IS NULL. The WHERE d.id IS NULL keeps only employees with no department (Jonas). I ran it: 11 rows, both 142000.00 rows present.
  5. UNION ALL is also faster, because it skips the de-duplication step.
Open in topic →

MySQL doesn't support FULL OUTER JOIN. How do you get one?

Show answer

"I combine a LEFT JOIN with the unmatched rows of a RIGHT JOIN. The quick version is LEFT JOIN UNION RIGHT JOIN, but UNION removes all duplicate rows, so if the selected columns can legitimately repeat it loses data. The correct version is the LEFT JOIN, then UNION ALL, then the RIGHT JOIN filtered to rows where the left table's key IS NULL. That keeps every matched row exactly once and adds only the right-side orphans."

Open in topic →

When would you use a CROSS JOIN?

Show answer

"When I really want every combination. The common case is building a grid, like every product times every store or every customer times every month, and then LEFT JOINing the actual data onto it so missing combinations show up as zeros instead of disappearing from the report. It's also how you generate test data or attach a single-row settings table to every row. Unintentional cross joins, from a missing join condition, are a classic cause of exploding row counts."

Open in topic →

How do you find each employee's manager when both are in the same table?

Show answer

"With a self join: list the employees table twice with different aliases, e for the employee and m for the manager, and join on m.id = e.manager_id. I use a LEFT JOIN so the person at the top, whose manager_id is NULL, still appears. Once both rows sit side by side I can compare them, for example WHERE e.salary > m.salary to find people earning more than their manager. For an unknown number of levels I'd switch to a recursive CTE."

Open in topic →

How do you join several tables without getting wrong totals?

Show answer

"I follow the foreign keys one join at a time and keep track of the grain, meaning what one row of the result represents. Every one-to-many join multiplies rows, so after joining orders to order items I have one row per line, and summing line values is right but counting orders needs COUNT DISTINCT, and summing anything from the customer or order level would double count. For those I pre-aggregate the child table in a derived table or CTE and join that. And once a chain starts with a LEFT JOIN, every later join that depends on the optional table has to be LEFT as well, or the unmatched rows disappear."

Open in topic →

How do you find customers who have never placed an order?

Show answer

"With an anti-join. My first choice is WHERE NOT EXISTS with a correlated subquery on orders.customer_id = customers.id, because it states the question directly, returns each customer once and isn't affected by NULLs. LEFT JOIN orders and then WHERE orders.id IS NULL is equivalent, and modern MySQL plans both as an antijoin. I avoid NOT IN unless the column is NOT NULL, because a single NULL in the subquery makes NOT IN return no rows at all."

Open in topic →

ON or WHERE?

You want every customer and, if they have one, their paid order. Which query is right, and what does the wrong one return?

SQL
-- A
SELECT c.name, o.id FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid';
-- B
SELECT c.name, o.id FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'paid';
Show answer

A is right: all six customers, with order ids only for Rohit (2) and Noah (7). B returns only Rohit and Noah.

Result
+-------+------+
| name  | id   |
+-------+------+
| Rohit |    2 |
| Maya  | NULL |
| Liam  | NULL |
| Sofia | NULL |
| Noah  |    7 |
| Zara  | NULL |
+-------+------+
6 rows in set (0.001 sec)

+-------+------+
| name  | id   |
+-------+------+
| Rohit |    2 |
| Noah  |    7 |
+-------+------+
2 rows in set (0.000 sec)
What’s happening
  1. In A, status = 'paid' is a matching rule. Each customer is matched only with paid orders; everyone else keeps one row with o.id = NULL.
  2. In B the join matches all orders first, then WHERE keeps only rows whose status is 'paid'. Customers whose orders are all unpaid lose every row, and Zara's NULL-padded row fails NULL = 'paid'.
  3. The first result above is A, the second B. It's the same pattern as the shipped-orders example in LEFT and RIGHT OUTER JOIN. The general rule: filters on the right-hand table of a LEFT JOIN go in ON.
Open in topic →

What's the difference between putting a condition in ON and in WHERE?

Show answer

"For an inner join, none in the result: both just exclude rows. For a left join they're different. Conditions in ON control which right-hand rows match, and left rows with no match are still returned with NULLs. Conditions in WHERE are applied after the join, so a condition on a right-table column throws away the NULL-padded rows and turns the left join into an inner join. So filters on the optional table go in ON, filters on the preserved table go in WHERE. USING is shorthand for an equality on same-named columns and merges them into one column; NATURAL JOIN does that for every shared name automatically, which I avoid."

Open in topic →

How does MySQL execute a join?

Show answer

"It joins tables one at a time in an order the cost-based optimizer chooses. The default algorithm is a nested-loop join: for each row of the driving table it looks up matches in the next table, ideally through an index, which shows up as eq_ref for a primary or unique key and ref for a non-unique index. If there's no usable index for an equality join, MySQL 8.0.18 and later use a hash join: build an in-memory hash table from the smaller input and probe it with the other, which replaced the old block nested-loop join. I check the plan with EXPLAIN or EXPLAIN ANALYZE, and the usual fix for a slow join is an index on the inner table's join column."

Open in topic →

"What do aggregate functions do with NULLs?"

Show answer

They ignore them. SUM, AVG, MIN, MAX and COUNT(column) only look at non-NULL values, so AVG divides by the number of non-NULL values, not the number of rows. Only COUNT(*) counts rows regardless of contents. And on an empty set, COUNT returns 0 while SUM, AVG, MIN and MAX return NULL, so wrap them in COALESCE if the application expects a number.

Open in topic →

Predict the result

SQL
SELECT SUM(price), COUNT(*), COALESCE(MAX(price), 0)
FROM products
WHERE price > 5000;
Show answer

One row: NULL, 0, 0.

What’s happening
  1. No product costs more than 5000 (the most expensive is the MacBook Air at 1299.00), so the WHERE lets zero rows through.
  2. There's no GROUP BY, so the query still returns exactly one row.
  3. SUM(price) over nothing is NULL; COUNT(*) is 0.
  4. MAX(price) is NULL too, and COALESCE replaces it with 0.
  5. If you added GROUP BY category_id, you'd get no rows at all: there would be zero groups, and grouping never invents an empty one.
Open in topic →

"COUNT(*) vs COUNT(column)?"

Show answer

COUNT(*) counts rows. COUNT(column) counts rows where that column isn't NULL. COUNT(DISTINCT column) counts different non-NULL values. The classic bug is COUNT(*) after a LEFT JOIN: a parent with no children still produces one padded row, so it gets 1 instead of 0 — count the child's primary key instead. COUNT(1) is just COUNT(*); there's no performance difference.

Open in topic →

Spot the bug

"Number of employees per department, including empty departments":

SQL
SELECT d.name, COUNT(*) AS headcount
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name;
Show answer

Research shows a headcount of 1 instead of 0.

SQL
SELECT d.name, COUNT(*) AS wrong, COUNT(e.id) AS headcount
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name;
Result
+-------------+-------+-----------+
| name        | wrong | headcount |
+-------------+-------+-----------+
| Engineering |     4 |         4 |
| Research    |     1 |         0 |
| Sales       |     3 |         3 |
| Support     |     2 |         2 |
+-------------+-------+-----------+
4 rows in set (0.000 sec)
What’s happening
  1. Research has no employees, so the LEFT JOIN produces one row for it with e.id, e.name and so on all NULL.
  2. COUNT(*) counts that padded row → 1.
  3. COUNT(e.id) ignores it because e.id is NULL → 0. Engineering, Sales and Support are unaffected because every one of their joined rows has a real e.id.
  4. Also notice Jonas (no department) doesn't appear at all: he's on the optional side of this join, and only departments drive the rows.
Open in topic →

"How does GROUP BY work?"

Show answer

It partitions the rows that survived WHERE into groups, one per distinct combination of the grouping columns (all NULLs form one group), then evaluates every aggregate once per group and returns one row per group. Every selected column must be a grouping column, an aggregate, or something that depends on the grouping columns. It doesn't guarantee any order in MySQL 8+, so add ORDER BY if you need one. Internally MySQL either scans an index in key order or builds a temporary table (hash) of groups.

Open in topic →

"What's the difference between WHERE and HAVING?"

Show answer

WHERE filters individual rows before grouping, so it can't use aggregates. HAVING filters groups after aggregation, so it's where conditions like COUNT(*) > 5 go. The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Anything that doesn't need an aggregate belongs in WHERE, because it shrinks the data before the expensive grouping step and can use indexes.

Open in topic →

Predict the result

SQL
SELECT department_id, COUNT(*) AS n
FROM employees
WHERE salary > 100000
GROUP BY department_id
HAVING n > 1;
Show answer

One row: department 1 with n = 4.

SQL
SELECT department_id, COUNT(*) AS n
FROM employees
WHERE salary > 100000
GROUP BY department_id
HAVING n > 1;
Result
+---------------+---+
| department_id | n |
+---------------+---+
|             1 | 4 |
+---------------+---+
1 row in set (0.000 sec)
What’s happening
  1. WHERE salary > 100000 keeps Asha, Ben, Chloe, Dev (department 1) and Elena (department 2). Everyone else earns 99000 or less.
  2. Grouping gives department 1 → 4 rows, department 2 → 1 row.
  3. HAVING n > 1 (MySQL allows the alias) drops department 2.
  4. Swap the filters — WHERE on count is impossible, but HAVING AVG(salary) > 100000 with no WHERE would return departments 1 and 2 (averages 146750 and 108000), a completely different question.
Open in topic →

"What is ONLY_FULL_GROUP_BY?"

Show answer

It's the SQL mode, on by default since MySQL 5.7.5, that rejects queries whose select list, HAVING or ORDER BY uses a column that's neither grouped, aggregated nor functionally dependent on the grouping columns — ERROR 1055. Without it MySQL returns an arbitrary value from each group, which is a silent bug. MySQL recognises dependencies through primary keys and unique NOT NULL columns, so GROUP BY customers.id lets you select customers.name. For a deliberate "any value" there's ANY_VALUE().

Open in topic →

"How do you add subtotals and a grand total in SQL?"

Show answer

GROUP BY a, b WITH ROLLUP (or GROUP BY ROLLUP(a, b)) adds super-aggregate rows: one subtotal per a with b NULL and a grand total with both NULL. GROUPING(col) returns 1 on rows where that column was rolled up, which separates them from real NULLs and lets you label or sort them. MySQL doesn't run CUBE or GROUPING SETS on InnoDB, so other combinations need UNION ALL; PostgreSQL has all three.

Open in topic →

"How do you get a comma-separated list per group?"

Show answer

In MySQL, GROUP_CONCAT(col ORDER BY … SEPARATOR ', ') with GROUP BY; in PostgreSQL, string_agg(col, ', ' ORDER BY …). The trap is group_concat_max_len, 1024 bytes by default, which truncates with only a warning. For results an application will parse, JSON_ARRAYAGG/JSON_OBJECTAGG are safer, and they can nest JSON_OBJECT to return a whole parent-with-children document in one query.

Open in topic →

"How do you pivot rows into columns in MySQL?"

Show answer

With conditional aggregation: group by the row key and write one SUM(CASE WHEN category = 'X' THEN amount ELSE 0 END) AS X per output column — it does everything in one scan. MySQL has no PIVOT operator (SQL Server does) and no FILTER clause (PostgreSQL does). If the column set isn't known in advance, build the statement with GROUP_CONCAT and run it as a prepared statement, or pivot in the application.

Open in topic →

Predict the result

SQL
SELECT SUM(CASE WHEN salary > 100000 THEN 1 END) AS high,
       SUM(CASE WHEN salary > 500000 THEN 1 END) AS very_high,
       COUNT(CASE WHEN salary > 500000 THEN 1 END) AS very_high_count
FROM employees;
Show answer

high = 5, very_high = NULL, very_high_count = 0.

SQL
SELECT SUM(CASE WHEN salary > 100000 THEN 1 END) AS high,
       SUM(CASE WHEN salary > 500000 THEN 1 END) AS very_high,
       COUNT(CASE WHEN salary > 500000 THEN 1 END) AS very_high_count
FROM employees;
Result
+------+-----------+-----------------+
| high | very_high | very_high_count |
+------+-----------+-----------------+
|    5 |      NULL |               0 |
+------+-----------+-----------------+
1 row in set (0.000 sec)
What’s happening
  1. With no ELSE, each CASE returns 1 for matching rows and NULL for the rest.
  2. Five employees earn more than 100000 (Asha, Ben, Chloe, Dev, Elena), so high sums five 1s → 5.
  3. Nobody earns more than 500000, so very_high sums ten NULLs. SUM ignores them, has nothing left, and returns NULL.
  4. COUNT of ten NULLs is 0. That's why SUM(CASE … ELSE 0 END) or COUNT(CASE … END) is the safer habit for counting.
Open in topic →

"What kinds of subqueries are there?"

Show answer

By shape: scalar (one value, usable anywhere an expression is), column (a list, used with IN/ANY/ALL/EXISTS), row, and table subqueries (in FROM, called derived tables). By dependency: uncorrelated subqueries run once on their own; correlated ones reference the outer query and are logically re-evaluated per outer row. A scalar subquery returning several rows is ERROR 1242; returning none gives NULL.

Open in topic →

"What is a correlated subquery and why can it be slow?"

Show answer

It's a subquery that references a column from the outer query, so logically it's re-evaluated for each outer row. Without a supporting index that means one inner scan per outer row — O(n·m). MySQL shows it as a "dependent" subquery in EXPLAIN, and sometimes rewrites it into a join (semijoin for IN/EXISTS). Usual fixes: index the correlated column, or compute the aggregates once in a derived table or with a window function and join.

Open in topic →

Predict the result

SQL
SELECT name
FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees x WHERE x.department_id = e.department_id)
ORDER BY name;
Show answer

Asha, Elena and Hiro — but not Jonas.

SQL
SELECT name
FROM employees e
WHERE salary = (SELECT MAX(salary) FROM employees x WHERE x.department_id = e.department_id)
ORDER BY name;
Result
+-------+
| name  |
+-------+
| Asha  |
| Elena |
| Hiro  |
+-------+
3 rows in set (0.000 sec)
What’s happening
  1. For each employee, the subquery returns the highest salary in that employee's department.
  2. Engineering's max is 185000 (Asha), Sales' 130000 (Elena), Support's 88000 (Hiro). Each matches only its own top earner.
  3. Jonas is the only person with no department and would be "top of his group" in a GROUP BY department_id, but here x.department_id = NULL matches nobody, the MAX is NULL, and 91000 = NULL isn't true.
  4. To include him you'd need a NULL-safe comparison: x.department_id <=> e.department_id.
Open in topic →

"IN vs EXISTS — which is faster, and what's the NOT IN problem?"

Show answer

In modern MySQL (8.0.16+) and PostgreSQL they usually get the same semijoin plan, so pick by meaning. The real difference is NULLs: NOT IN (subquery) returns no rows at all if the subquery produces a single NULL, because x <> NULL is unknown. NOT EXISTS (or LEFT JOIN … WHERE child.id IS NULL) doesn't have that problem, so it's the safe default for anti-joins.

Open in topic →

Spot the bug

"Products that have never been ordered":

SQL
SELECT name FROM products
WHERE id NOT IN (SELECT product_id FROM order_items);

Does this suffer from the NULL trap?

Show answer

No — it correctly returns the iPhone 17. order_items.product_id is NOT NULL (it's part of the primary key), so the list can never contain a NULL.

SQL
SELECT name FROM products
WHERE id NOT IN (SELECT product_id FROM order_items);
Result
+-----------+
| name      |
+-----------+
| iPhone 17 |
+-----------+
1 row in set (0.000 sec)
What’s happening
  1. The subquery lists every ordered product id; product 4 (iPhone 17) never appears.
  2. Because product_id is declared NOT NULL, every id <> product_id comparison is definitely true or false, so NOT IN behaves.
  3. The trap only appears when the subquery column is nullable — like employees.manager_id, or any column that comes from the optional side of a LEFT JOIN.
  4. The habit to build: reach for NOT EXISTS and you never have to check.
Open in topic →

"What's a derived table, and how is it different from a CTE or a view?"

Show answer

A derived table is a subquery in FROM with a mandatory alias; it exists only for that statement and can only be referenced once, where it's written. A CTE is the same idea with a name declared up front in WITH, so it can be referenced several times and can be recursive. A view is a stored, named query in the schema that any statement can use. The optimizer treats all three similarly: merge into the outer query when possible, otherwise materialise.

Open in topic →

"Why use a CTE instead of a subquery?"

Show answer

Readability and reuse: a CTE names each step and reads top to bottom, can be referenced more than once in the same statement (materialised once), and can be recursive, which a derived table can't. Performance is usually the same as a derived table since the optimizer merges or materialises both the same way. CTEs need MySQL 8.0+; on 5.7 you'd use derived tables or temporary tables.

Open in topic →

"How do you query a hierarchy in SQL?"

Show answer

With a recursive CTE: an anchor selects the root rows, and a recursive member joins the base table to the CTE to fetch the next level, combined with UNION ALL; it repeats until a level comes back empty. Carry a depth and a path column to indent or sort the tree, cast string columns wide enough in the anchor, and guard against cycles. MySQL caps recursion at cte_max_recursion_depth (1000 by default). Before MySQL 8 you needed a fixed number of self-joins, a closure table or nested sets.

Open in topic →

"What's the difference between GROUP BY and a window function?"

Show answer

GROUP BY collapses rows into one per group, so detail columns are lost. A window function computes over a set of related rows — the partition — but keeps every row, adding the result as a column. That's why "each employee with their department average" is a one-liner with AVG(salary) OVER (PARTITION BY department_id). Window functions run after WHERE/GROUP BY/HAVING, so you can't filter on them directly; wrap the query in a CTE and filter outside.

Open in topic →

"Explain ROW_NUMBER vs RANK vs DENSE_RANK."

Show answer

All three number rows in the window's order; they differ on ties. ROW_NUMBER gives every row a unique number and breaks ties arbitrarily (add a tie-breaker to make it deterministic). RANK gives ties the same rank and then skips — 1, 2, 2, 4. DENSE_RANK gives ties the same rank without gaps — 1, 2, 2, 3. For "Nth highest salary" use DENSE_RANK, because with a tie at second place RANK has no row ranked 3.

Open in topic →

Predict the result

Sales salaries are Elena 130000, Grace 99000, Farid 95000. What does this return?

SQL
SELECT name,
       RANK()       OVER (ORDER BY department_id) AS r,
       DENSE_RANK() OVER (ORDER BY department_id) AS dr,
       ROW_NUMBER() OVER (ORDER BY department_id, id) AS rn
FROM employees
WHERE department_id IN (2, 3)
ORDER BY rn;
Show answer

Everyone in Sales ties on department_id, and so does everyone in Support.

SQL
SELECT name,
       RANK()       OVER (ORDER BY department_id) AS r,
       DENSE_RANK() OVER (ORDER BY department_id) AS dr,
       ROW_NUMBER() OVER (ORDER BY department_id, id) AS rn
FROM employees
WHERE department_id IN (2, 3)
ORDER BY rn;
Result
+-------+---+----+----+
| name  | r | dr | rn |
+-------+---+----+----+
| Elena | 1 |  1 |  1 |
| Farid | 1 |  1 |  2 |
| Grace | 1 |  1 |  3 |
| Hiro  | 4 |  2 |  4 |
| Isla  | 4 |  2 |  5 |
+-------+---+----+----+
5 rows in set (0.000 sec)
What’s happening
  1. The window orders by department_id only, so the three Sales rows are all peers (value 2) and the two Support rows are peers (value 3). Salary plays no part.
  2. RANK(): the Sales rows are all 1; Support starts at 4, because three rows come before it.
  3. DENSE_RANK(): Sales 1, Support 2 — one step per distinct value.
  4. ROW_NUMBER() with the id tie-breaker numbers them 1 to 5 in id order: Elena, Farid, Grace, Hiro, Isla.
  5. The lesson: ranks are about the ORDER BY inside OVER, not about whatever column you happen to be thinking of.
Open in topic →

"How do you compare each row with the previous one?"

Show answer

LAG(col) OVER (PARTITION BY group ORDER BY time) returns the previous row's value in that order (and LEAD the next one), so col - LAG(col) OVER (…) is the change. The first row of each partition gets NULL, or the default you pass as the third argument. Running totals are SUM(col) OVER (ORDER BY time). Before window functions you'd self-join each row to the row with the greatest smaller timestamp, which is both harder to write and slower.

Open in topic →

"What's the difference between ROWS and RANGE?"

Show answer

ROWS frames count physical rows relative to the current one; RANGE frames are defined by values of the ORDER BY key, so peers — rows with the same value — are always in or out together, and offsets can be values like INTERVAL 30 DAY. The default frame with an ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is why a running total jumps by the whole tie at once and why LAST_VALUE returns the current row unless you extend the frame to UNBOUNDED FOLLOWING.

Open in topic →

Predict the result

SQL
SELECT name, salary,
       MAX(salary) OVER (ORDER BY salary DESC) AS a,
       MIN(salary) OVER (ORDER BY salary DESC) AS b
FROM employees
WHERE department_id = 1;
Show answer

a is 185000.00 on every row; b shrinks down the list: 185000, 142000, 142000, 118000.

SQL
SELECT name, salary,
       MAX(salary) OVER (ORDER BY salary DESC) AS a,
       MIN(salary) OVER (ORDER BY salary DESC) AS b
FROM employees
WHERE department_id = 1;
Result
+-------+-----------+-----------+-----------+
| name  | salary    | a         | b         |
+-------+-----------+-----------+-----------+
| Asha  | 185000.00 | 185000.00 | 185000.00 |
| Ben   | 142000.00 | 185000.00 | 142000.00 |
| Chloe | 142000.00 | 185000.00 | 142000.00 |
| Dev   | 118000.00 | 185000.00 | 118000.00 |
+-------+-----------+-----------+-----------+
4 rows in set (0.000 sec)
What’s happening
  1. With ORDER BY in OVER, the default frame is "from the first row up to the current row and its peers".
  2. Ordered by salary descending, the first row is always Asha (185000), so MAX over any frame starting there is 185000.00.
  3. MIN over "Asha up to the current row" is the current row's salary (it's the smallest seen so far). On Ben's row the frame includes his peer Chloe, but she has the same salary, so b is 142000.00 for both.
  4. Without ORDER BY in OVER, both would be the department's overall max and min on every row.
Open in topic →

"How do you get the top N rows per group?"

Show answer

Number rows inside each group with a window function in a CTE, then filter: WITH r AS (SELECT …, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY score DESC, id) AS rn FROM t) SELECT * FROM r WHERE rn <= N. Pick the function by how ties should behave — ROW_NUMBER for exactly N, RANK or DENSE_RANK to include ties. Alternatives are a LATERAL subquery with ORDER BY … LIMIT N (fast with an index on (grp, score)), a correlated MAX subquery for top-1, or the anti-join self-join that was the standard answer before MySQL 8.

Open in topic →

Spot the bug

"Each department's highest-paid employee":

SQL
SELECT department_id, name, MAX(salary)
FROM employees
GROUP BY department_id;
Show answer

name isn't grouped or aggregated, so MySQL 9.7 rejects it with ERROR 1055; with ONLY_FULL_GROUP_BY off, it would return an arbitrary name next to the maximum. MAX gives the top value, never the row it came from.

SQL
WITH r AS (
  SELECT department_id, name, salary,
         RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT department_id, name, salary FROM r WHERE rnk = 1 ORDER BY department_id;
Result
+---------------+-------+-----------+
| department_id | name  | salary    |
+---------------+-------+-----------+
|          NULL | Jonas |  91000.00 |
|             1 | Asha  | 185000.00 |
|             2 | Elena | 130000.00 |
|             3 | Hiro  |  88000.00 |
+---------------+-------+-----------+
4 rows in set (0.000 sec)
What’s happening
  1. RANK() numbers each department's employees from the top salary; ties at the top would all get 1.
  2. WHERE rnk = 1 keeps the top row(s) per department, with the right name attached: Jonas (NULL department), Asha, Elena and Hiro.
  3. This is the general fix for "the row behind an aggregate" — see also ONLY_FULL_GROUP_BY.
Open in topic →

"UNION vs UNION ALL? Does MySQL support INTERSECT and EXCEPT?"

Show answer

UNION stacks the results and removes duplicate rows, which costs a sort or hash; UNION ALL keeps everything and is cheaper, so prefer it when duplicates can't occur. Columns are matched by position and named after the first query, and ORDER BY/LIMIT at the end apply to the whole result. INTERSECT and EXCEPT (with ALL variants) exist since MySQL 8.0.31; INTERSECT has higher precedence. Before that you'd write them with EXISTS and NOT EXISTS.

Open in topic →

Predict the result

SQL
SELECT 1 AS n UNION SELECT 2 UNION SELECT 2 INTERSECT SELECT 3;
Show answer

Two rows: 1 and 2.

SQL
SELECT 1 AS n UNION SELECT 2 UNION SELECT 2 INTERSECT SELECT 3;
Result
+---+
| n |
+---+
| 1 |
| 2 |
+---+
2 rows in set (0.000 sec)
What’s happening
  1. INTERSECT is evaluated first: SELECT 2 INTERSECT SELECT 3 is empty (no value is in both).
  2. That leaves SELECT 1 UNION SELECT 2 UNION (empty), which is {1, 2}.
  3. Reading it left to right instead — (1 ∪ 2 ∪ 2) ∩ 3 — would give an empty result. Precedence matters; parenthesise mixed set operations.
Open in topic →
InterviewCh 06 INSERT

"How do you get the id of a row you just inserted?"

Show answer

In MySQL, LAST_INSERT_ID() returns the first AUTO_INCREMENT value generated by the most recent insert on the same connection (drivers expose it as insertId), so concurrent inserts by other clients don't interfere. For a multi-row insert it's the first row's id; don't assume the other rows' ids follow on consecutively (with InnoDB's default interleaved lock mode, concurrent inserts can interleave), so query them back by a natural key if you need them all. Never use SELECT MAX(id) — another session may have inserted in between. PostgreSQL uses INSERT … RETURNING id.

Open in topic →

Predict the result

SQL
INSERT INTO departments (id, name) VALUES (5, 'Legal'), (6, 'Sales'), (7, 'Design');
SELECT COUNT(*) FROM departments;
Show answer

The insert fails and COUNT(*) is still 4.

SQL
INSERT INTO departments (id, name) VALUES (5, 'Legal'), (6, 'Sales'), (7, 'Design');
SELECT COUNT(*) FROM departments;
Result
ERROR 1062 (23000): Duplicate entry 'Sales' for key 'departments.name'
+----------+
| COUNT(*) |
+----------+
|        4 |
+----------+
1 row in set (0.000 sec)
What’s happening
  1. departments.name is UNIQUE, and 'Sales' already exists (department 2).
  2. The second row fails with ERROR 1062 (23000): Duplicate entry 'Sales' for key 'departments.name'.
  3. InnoDB rolls back the whole statement, including the Legal row that was already written, so no rows are added.
  4. The count stays at the original four. To insert the good rows and skip the bad one you'd use INSERT IGNORE (see INSERT IGNORE and REPLACE) — with its own risks.
Open in topic →

"How would you copy or archive rows from one table into another?"

Show answer

INSERT INTO target (cols) SELECT … FROM source WHERE …, which stays inside the server and can join, filter and aggregate on the way. Columns are matched by position, so list them explicitly. For archiving, do the INSERT … SELECT and the DELETE in one transaction, in primary-key batches to keep locks short. CREATE TABLE new LIKE old copies the structure with indexes; CREATE TABLE new AS SELECT copies only the result set and its column types.

Open in topic →
InterviewCh 06 UPDATE

"What does UPDATE return, and why might it report 0 rows for a row that exists?"

Show answer

MySQL reports rows matched (met the WHERE) and rows changed; the affected-rows count drivers return is the changed count by default, so setting a column to its current value reports 0 even though the row exists. Use the driver's matched count (CLIENT_FOUND_ROWS) if you need "did the row exist". Also remember MySQL evaluates single-table SET assignments left to right using already-updated values, unlike PostgreSQL and the standard.

Open in topic →

"How do you update a table based on values in another table?"

Show answer

In MySQL, a multi-table update: UPDATE a JOIN b ON … SET a.col = b.col WHERE …; it can even set columns in both tables. PostgreSQL uses UPDATE a SET col = b.col FROM b WHERE a.id = b.a_id. Watch for join fan-out — a target row matched several times is updated once with an arbitrary match, so aggregate the source first. Multi-table forms can't use ORDER BY/LIMIT, and multi-table deletes can trip over foreign keys, so delete children before parents.

Open in topic →

"DELETE vs TRUNCATE vs DROP?"

Show answer

DELETE is DML: it removes the rows matching a WHERE, one by one, fires triggers, respects foreign keys and can be rolled back, but it's slow on big tables and doesn't reset AUTO_INCREMENT. TRUNCATE is DDL: it drops and recreates the table, so it's fast, resets AUTO_INCREMENT, doesn't fire triggers, commits implicitly and can't be rolled back, and InnoDB refuses it if another table's foreign key references the table. DROP removes the table itself along with its data, indexes and privileges on it.

Open in topic →

"How do you do an upsert in MySQL?"

Show answer

INSERT … ON DUPLICATE KEY UPDATE — it inserts the row, and if that would violate any primary key or unique index, it updates the existing row instead, atomically. Refer to the incoming values with a row alias, VALUES (…) AS new … SET col = new.col (MySQL 8.0.19+); the old VALUES(col) function is deprecated. Affected rows are 1 for insert, 2 for update, 0 for no change. Watch out for tables with several unique keys and for AUTO_INCREMENT values consumed by the update path. PostgreSQL's equivalent is INSERT … ON CONFLICT (cols) DO UPDATE SET col = EXCLUDED.col.

Open in topic →

"INSERT IGNORE vs REPLACE vs ON DUPLICATE KEY UPDATE?"

Show answer

INSERT IGNORE skips rows that would cause errors — duplicates, but also foreign-key failures — and downgrades data errors to warnings, so invalid values can be stored silently. REPLACE deletes the conflicting row and inserts a new one: unspecified columns reset to defaults, a new AUTO_INCREMENT id may be assigned, and on a referenced row it either fails on the foreign key or cascades and deletes the children. ON DUPLICATE KEY UPDATE updates the existing row in place, keeping other columns, and is the right tool for upserts.

Open in topic →

"How would you insert a million rows quickly?"

Show answer

Cut per-statement overhead: batch rows into multi-row INSERTs (hundreds to thousands per statement, within max_allowed_packet), wrap batches in transactions so you don't pay a redo-log flush per row, or use LOAD DATA [LOCAL] INFILE, which is the fastest because it skips per-row SQL parsing. Load in primary-key order, consider adding secondary indexes after the load, and keep transactions to manageable chunks so undo and replication lag stay bounded. Single-row autocommit inserts are the slowest by far — about 50× slower than batching in our 10,000-row test.

Open in topic →

"Someone ran an UPDATE without a WHERE in production. What now, and how do you prevent it?"

Show answer

If the transaction hasn't been committed, roll it back. If it has, restore: take the latest backup to a separate server, replay the binary log up to just before the bad statement (point-in-time recovery), and copy the affected column values back — or use the binlog's before-images (row-based logging) to reverse it. Prevention is layered: sql_safe_updates or --safe-updates for interactive sessions, least-privilege accounts, changes reviewed and run inside transactions after a SELECT preview, and tested backups with binlogs retained.

Open in topic →

Spot the bug

"Mark every order of customers in Toronto as shipped" (read it rather than run it: with safe updates off it really changes orders 2 and 7; to try it, wrap it in START TRANSACTION; … ROLLBACK;):

SQL
UPDATE orders
SET status = 'shipped'
WHERE customer_id IN (SELECT id FROM customers WHERE city = 'Toronto')
   OR status = 'paid';
Show answer

The OR status = 'paid' applies to all customers, so Toronto's orders and every paid order anywhere get shipped.

Starting dataOrder 9 removed

What else IGNORE swallows stored order 9 for customer 1 with an empty status. Customer 1 is in Toronto, so it would show up here as well; delete it first:

SQL
DELETE FROM orders WHERE id = 9;
SQL
SELECT id, customer_id, status FROM orders
WHERE customer_id IN (SELECT id FROM customers WHERE city = 'Toronto')
   OR status = 'paid';
Result
+----+-------------+---------+
| id | customer_id | status  |
+----+-------------+---------+
|  1 |           1 | shipped |
|  2 |           1 | paid    |
|  7 |           5 | paid    |
+----+-------------+---------+
3 rows in set (0.000 sec)
What’s happening
  1. Previewing the WHERE as a SELECT shows which rows the UPDATE would touch.
  2. Toronto's customers are Rohit (1) and Noah (5): their orders are 1, 2 and 7.
  3. OR status = 'paid' adds every paid order regardless of city — in this data both paid orders (2 and 7) already belong to Toronto customers, so the result happens to look right.
  4. That's the dangerous part: on today's data the bug is invisible, and next week a paid order from Mumbai gets marked shipped. If the intent was "Toronto's paid orders", it's AND; if it really was "or", it should be a separate statement with its own review.
Open in topic →

What's the difference between CHANGE, MODIFY and RENAME COLUMN?

Show answer

"All three are ALTER TABLE clauses. RENAME COLUMN, from MySQL 8.0, only renames. MODIFY keeps the name but replaces the whole column definition — type, nullability, default — so anything I don't restate is lost. CHANGE does both at once: old name, new name and the full new definition; it's what you used on 5.7 to rename. For a pure rename I use RENAME COLUMN, and with MODIFY I always copy the full current definition from SHOW CREATE TABLE first."

Open in topic →

Predict the result

SQL
CREATE TABLE prices (p DECIMAL(4,1));
INSERT INTO prices VALUES (99.94), (99.95), (999.96);
SELECT * FROM prices;
Show answer

The insert fails and the table stays empty:

Result
ERROR 1264 (22003): Out of range value for column 'p' at row 3
Note (Code 1265): Data truncated for column 'p' at row 1
Note (Code 1265): Data truncated for column 'p' at row 2
Error (Code 1264): Out of range value for column 'p' at row 3

SELECT * FROM prices returns nothing (and SELECT COUNT(*) gives 0).

What’s happening
  1. DECIMAL(4,1) allows four digits, one after the point: the largest value is 999.9.
  2. Row 1, 99.94, rounds to 99.9 and row 2, 99.95, rounds half away from zero to 100.0. Both fit; each leaves a Note 1265 about the rounding.
  3. Row 3, 999.96, rounds to 1000.0, which needs five digits, so it's out of range — and the error says at row 3.
  4. A multi-row INSERT is one statement, and on InnoDB in strict mode a failed statement is rolled back as a unit: rows 1 and 2 aren't kept either. Insert the rows separately and the first two would be stored.
Open in topic →

CHAR vs VARCHAR vs TEXT?

Show answer

"CHAR is fixed width — padded with spaces, trailing spaces stripped on read — so I use it only for genuinely fixed-length codes like country or currency codes. VARCHAR is variable length with a 1–2 byte length prefix and is my default; the length counts characters, not bytes. TEXT is for long, unbounded text: it can live off-page, it needs a prefix length to be indexed, and it makes temporary tables heavier. Whatever the type, I use utf8mb4, because MySQL's utf8 is the three-byte utf8mb3 and can't store emoji."

Open in topic →

DATETIME or TIMESTAMP?

Show answer

"DATETIME stores the date and time exactly as given, no time zone, from year 1000 to 9999. TIMESTAMP stores an instant in UTC and converts to and from the session's time zone, but only from 1970 to January 2038 because it's a 32-bit epoch. TIMESTAMP also hits daylight-saving gaps — a non-existent local time is rejected. My default is DATETIME holding UTC, with the connection time zone set to UTC and conversion done in the application for display. I'd use TIMESTAMP only where its automatic conversion is actually wanted and 2038 isn't a concern."

Open in topic →

When would you use a JSON column in MySQL?

Show answer

"For data whose shape varies per row and that I mostly read as a whole — product attributes, settings, raw API payloads. MySQL validates it and stores it in a binary format, I read fields with -> and ->>, update them with JSON_SET, and turn arrays into rows with JSON_TABLE. It can't index the whole document, so anything I filter on gets a functional index or a generated column, and arrays get a multi-valued index for MEMBER OF. Fields I join or filter on all the time become real columns."

Open in topic →

Would you use ENUM for a status column?

Show answer

"For a short, stable list, yes: it's one or two bytes, it rejects invalid values in strict mode and it documents the allowed values in the schema. The catches are that it sorts by declaration order, adding a value is an ALTER — instant only if I append at the end — and reordering rewrites the table. If the list changes often, or statuses need attributes like 'is final', I use a lookup table with a foreign key instead. And BOOLEAN in MySQL is just TINYINT(1), so I add a CHECK if I need it to really be 0 or 1."

Open in topic →

AUTO_INCREMENT or UUID for a primary key?

Show answer

"In InnoDB the primary key is the clustered index and every secondary index stores it, so I want it small and increasing. AUTO_INCREMENT BIGINT is the default: inserts append to the end of the tree. UUIDs help when ids are created outside the database or across services, but a random UUIDv4 scatters inserts — in my test it was 2.7 times slower to load and 70% bigger. If I need UUIDs I use a time-ordered one, UUIDv7 or UUID_TO_BIN with the swap flag, stored as BINARY(16), not CHAR(36). AUTO_INCREMENT has gaps from rollbacks and failed inserts, so it's not a gap-free sequence."

Open in topic →

What are referential actions, and which would you use?

Show answer

"They define what happens to child rows when a parent row is deleted or its key is updated. RESTRICT, or NO ACTION, which in InnoDB is the same thing, refuses the delete if children exist; CASCADE deletes or updates the children too; SET NULL keeps them with a NULL foreign key. I choose per relationship: CASCADE for dependent data like cart items, SET NULL for history I want to keep without the parent, RESTRICT for things like orders and payments. The whole statement, cascades included, is atomic. In InnoDB the child column gets an index automatically, and since MySQL 9.6 cascades are handled by the server so they can show up in the binlog."

Open in topic →

Spot the bug

A team wants "each customer can have at most one coupon redemption per coupon", and writes:

SQL
CREATE TABLE redemptions (
  id          INT AUTO_INCREMENT PRIMARY KEY,
  coupon_id   INT NOT NULL,
  customer_id INT NULL,
  UNIQUE (coupon_id, customer_id)
);

Guest checkouts insert customer_id = NULL. What goes wrong?

Show answer

Nothing stops a guest from redeeming the same coupon any number of times:

SQL
INSERT INTO redemptions (coupon_id, customer_id) VALUES (5, NULL), (5, NULL), (5, NULL), (5, 1);
INSERT INTO redemptions (coupon_id, customer_id) VALUES (5, 1);
SELECT * FROM redemptions;
Result
ERROR 1062 (23000): Duplicate entry '5-1' for key 'redemptions.coupon_id'
+----+-----------+-------------+
| id | coupon_id | customer_id |
+----+-----------+-------------+
|  1 |         5 |        NULL |
|  2 |         5 |        NULL |
|  3 |         5 |        NULL |
|  4 |         5 |           1 |
+----+-----------+-------------+
What’s happening
  1. A unique index compares the whole tuple. (5, NULL) vs (5, NULL): the second parts are NULL = NULL, which is unknown, so the tuples are not considered equal.
  2. So the unique index treats every row with a NULL in it as distinct, and three identical guest redemptions pass.
  3. For signed-in customers it works: a second (5, 1) fails with ERROR 1062 (the index is named after its first column, redemptions.coupon_id). The hole is exactly the rows where the rule mattered most.
  4. Fixes: track guests with a non-null identifier (an email or a guest id) and make the column NOT NULL, or index a generated column such as COALESCE(customer_id, -1) if one redemption for "all guests together" is really the rule. PostgreSQL 15+ also has UNIQUE NULLS NOT DISTINCT; MySQL has no equivalent.
Open in topic →

How do NULLs behave in a UNIQUE index?

Show answer

"In MySQL, and in standard SQL, a unique index allows any number of NULLs, because NULL isn't equal to anything, including another NULL. That's handy for optional values that must be unique when present, like a partner reference. But in a composite unique key, any row with a NULL in one of the columns escapes the rule, so if the rule must hold I make those columns NOT NULL. PostgreSQL 15 added NULLS NOT DISTINCT for this; MySQL doesn't have it."

Open in topic →

VIRTUAL or STORED generated column?

Show answer

"Both are computed from other columns of the row and can't be written directly. VIRTUAL is computed on read and takes no space, and adding one is an instant metadata change; I can still index it, and the index stores the value. STORED is computed on write and saved in the row, which costs space and a table rebuild to add, but makes reads free and is needed for some cases, like a column that's part of a foreign key. I usually pick VIRTUAL with an index for search keys like an email domain or a JSON field, and STORED for expensive expressions I read a lot."

Open in topic →

Predict what happens

A developer runs this on a busy 200 GB orders table during the day, with no ALGORITHM clause:

SQL
ALTER TABLE orders MODIFY status VARCHAR(20) NOT NULL;

status is currently ENUM('pending','paid','shipped','cancelled'). What does MySQL do?

Show answer

It quietly picks ALGORITHM=COPY: it rebuilds the whole 200 GB table row by row, converting each ENUM index to text, and blocks all writes to orders until it's done — likely hours. Reads continue (the copy takes a shared lock), but nobody can place an order.

What’s happening
  1. Changing an ENUM to a VARCHAR changes the stored format of every row (a 1-byte index becomes a length-prefixed string), so neither INSTANT nor INPLACE is possible.
  2. Without an ALGORITHM clause MySQL doesn't fail; it falls back to the cheapest algorithm that works — COPY — with the lock that requires, LOCK=SHARED.
  3. Had the developer written ALGORITHM=INPLACE, LOCK=NONE, MySQL would have refused immediately with ERROR 1846, and they'd have known to use gh-ost or pt-online-schema-change, or an expand/migrate/contract plan, instead.
  4. Even before the copy starts, the ALTER needs the metadata lock — so one forgotten open transaction would first queue all traffic behind it.
Open in topic →

How do you change a big table's schema without downtime?

Show answer

"First I check what the change needs. INSTANT changes like adding or dropping a column on 8.0.29+ are metadata only. INPLACE changes like adding an index allow concurrent writes. COPY changes like a column type change rebuild the table and block writes. I always write ALGORITHM and LOCK explicitly so MySQL fails fast instead of silently choosing COPY. Even instant changes need a metadata lock, so I set a short lock_wait_timeout and check for long-running transactions first, otherwise all traffic queues behind the ALTER. For real rewrites on big tables I use gh-ost or pt-online-schema-change, which copy in chunks and swap with a rename, or I split the change into expand, migrate and contract steps."

Open in topic →

What's the difference between a candidate key, a primary key and a surrogate key?

Show answer

"A candidate key is a minimal set of columns that's guaranteed unique — minimal meaning you can't remove a column and stay unique. A table can have several; customers has id and email. The primary key is the candidate key I choose as the official identity; foreign keys reference it and InnoDB clusters the table on it. The others become UNIQUE constraints. A surrogate key is one the database invents with no business meaning, like an auto-increment id, as opposed to a natural key like an email. I usually use a surrogate primary key because natural keys change and are wide, and I keep the natural key as a UNIQUE constraint."

Open in topic →

How do you model a many-to-many relationship?

Show answer

"With a junction table that has a foreign key to each side and one row per pair — for orders and products that's order_items with order_id and product_id. The pair is the primary key, so the same product can't be listed twice on an order, and I add a second index on the other column so I can search from either side. Attributes of the relationship itself, like quantity and the price at the time of purchase, go in the junction table, which is often how it becomes a real entity, an order line."

Open in topic →

What do you check when you read an ER diagram?

Show answer

"First the entities and their primary keys, then each relationship's cardinality at both ends — in crow's foot, the inner symbol is the maximum and the outer one the minimum, so a circle means optional and a crow's foot means many. I check that every many-to-many has a junction table, that optional relationships really have nullable foreign keys, and whether minimums like 'an order has at least one line' are enforced anywhere, because foreign keys can't express them. And I compare the diagram with the actual foreign keys in information_schema, because diagrams drift."

Open in topic →

What are update, insert and delete anomalies?

Show answer

"They're the problems you get when one fact is stored in many rows. Update anomaly: a customer's city is copied into every order row, so changing it means updating many rows, and if you miss one the data contradicts itself. Insert anomaly: you can't record a customer until they place an order, because the table's rows are orders. Delete anomaly: deleting a customer's last order deletes everything you knew about the customer. Normalisation fixes all three by giving each fact one home — customers, products and orders in their own tables, linked by keys."

Open in topic →

Which normal form does this break?

SQL
CREATE TABLE enrolments (
  student_id   INT,
  course_id    INT,
  course_title VARCHAR(100),
  grade        CHAR(2),
  PRIMARY KEY (student_id, course_id)
);
Show answer

2NF. course_title depends only on course_id, which is part of the composite key (student_id, course_id) — a partial dependency.

What’s happening
  1. Check 1NF first: every column holds a single value and there's a key, so it's in 1NF.
  2. For each non-key column, ask "do I need the whole key to know it?". grade — yes: a grade belongs to one student in one course.
  3. course_title — no: course_id alone determines it. Every student in course 42 repeats the same title, so renaming a course means updating every enrolment (an update anomaly), and a course with no students has nowhere to store its title (an insert anomaly).
  4. Fix: move course_title to courses (course_id PK, course_title) and keep enrolments (student_id, course_id, grade).
Open in topic →

And this one?

SQL
CREATE TABLE employees_copy (
  id              INT PRIMARY KEY,
  name            VARCHAR(50),
  department_id   INT,
  department_name VARCHAR(50)
);
Show answer

3NF. The key is the single column id, so 2NF is automatic, but department_name depends on department_id, a non-key column: id → department_id → department_name is a transitive dependency.

What’s happening
  1. A table whose primary key is one column can't have partial dependencies, so it's in 2NF.
  2. department_name doesn't depend on the employee directly; it depends on the department, and gets to the employee through department_id.
  3. Renaming "Sales" to "Revenue" would mean updating every Sales employee, and a department with no employees (Research, in the sample data) couldn't be stored. That's exactly why the sample schema has a separate departments table.
Open in topic →

Explain 1NF, 2NF and 3NF.

Show answer

"They're steps towards storing each fact once, defined by functional dependencies. 1NF: every column holds a single atomic value — no lists or repeating groups — and rows have a key. 2NF: no non-key column depends on only part of a composite key; for example in order lines keyed by order and product, the product name depends on the product alone, so it moves to a products table. 3NF: no non-key column depends on another non-key column; the customer's city depends on customer_id, not on the order, so it moves to customers. The usual summary is that every non-key attribute depends on the key, the whole key and nothing but the key. Each split must be lossless, which it is if you split along a real dependency so the join column is a key of one side."

Open in topic →

What's the difference between 3NF and BCNF?

Show answer

"3NF allows a functional dependency X → Y if X is a key or if Y is part of a candidate key. BCNF drops that second escape hatch: the left side of every dependency must be a super key. They only differ when a table has overlapping composite candidate keys — the classic case is student, course, instructor where each instructor teaches one course. That's 3NF but not BCNF, because instructor determines course without being a key. Decomposing it to BCNF removes the duplication, but you can lose the ability to enforce '(student, course) determines instructor' with a key, so sometimes 3NF is the pragmatic choice."

Open in topic →

Spot the bug in the trigger

The trg_items_au trigger from the main example handles quantity changes correctly. What happens when an order line is moved to another order?

SQL
UPDATE order_items SET order_id = 7 WHERE order_id = 6 AND product_id = 7;
SELECT o.id, o.items_total, SUM(oi.quantity * oi.unit_price) AS recomputed
FROM orders o JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id, o.items_total
HAVING o.items_total <> recomputed;
Show answer

Both orders end up wrong:

Result
+----+-------------+------------+
| id | items_total | recomputed |
+----+-------------+------------+
|  6 |      307.00 |     249.00 |
|  7 |     1016.00 |    1074.00 |
+----+-------------+------------+
What’s happening
  1. The trigger does items_total - OLD.amount + NEW.amount but only WHERE id = NEW.order_id — it assumes the line stays on the same order.
  2. Moving the line from order 6 to order 7: the trigger updates order 7 only, subtracting 58.00 and adding 58.00 — net zero. Order 7's total stays 1016.00 though it gained a line (1074.00 real).
  3. Order 6 is never touched, so it still includes the 58.00 it lost: 307.00 instead of 249.00.
  4. The fix subtracts from OLD.order_id and adds to NEW.order_id in two statements (a BEGIN … END trigger body). After recreating the trigger that way, repairing the totals with the backfill query, and moving the line back, the reconciliation query reports drifted_orders = 0.
  5. The general lesson: every write path to the source must be thought through — and the reconciliation query is what caught this.
Open in topic →

When would you denormalise?

Show answer

"Only after normalising, and for a measured reason — a frequent read that's slow because of joins or aggregation, like listing orders by total or showing a review count on every product page. I keep the source of truth normalised and treat the copy like a cache: it's updated in the same transaction, by a trigger or by the code path that changes the source, and I run a reconciliation query that recomputes it and reports drift. If it can be a generated column, I use that, because then it can't drift. For reports I'd rather build summary tables or use a separate analytics store than denormalise the OLTP tables."

Open in topic →

Design the database for an online shop.

Show answer

"I'd start with the entities: customers, addresses, categories, products — usually with variants that hold the SKU, price and stock — orders, order lines, payments and shipments. Customers to orders is one-to-many, orders to products is many-to-many through order lines, which also store the quantity and the unit price at the time of purchase. Orders snapshot the shipping address too, so later changes don't rewrite history. Payments are a ledger of charges and refunds with a unique provider reference so webhook retries can't double-charge, and the balance is a sum. I'd use surrogate keys, foreign keys everywhere, CHECK constraints on amounts and quantities, and decrement stock with a conditional update so we can't oversell. Then I'd list the main queries — order history, product page, admin reports — and add indexes for them."

Open in topic →

How would you implement soft deletes, and what are the pitfalls?

Show answer

"A nullable deleted_at timestamp: deleting sets it, and normal reads filter on deleted_at IS NULL — ideally through a view or an ORM scope so nobody forgets. The pitfalls: every query and report has to apply the filter; unique constraints still see deleted rows, so a user can't re-register with the same email unless uniqueness only covers live rows — a partial unique index in PostgreSQL, a generated column that's NULL for deleted rows plus a unique index in MySQL; foreign key cascades don't fire; the table keeps growing; and for personal data a soft delete isn't erasure, so you still need anonymisation or a purge job. For a full change history I'd use a history table filled by a trigger or from change data capture, since MySQL has no system-versioned tables."

Open in topic →

What is an index, and what does it cost?

Show answer

An index is a separate sorted structure — in InnoDB a B+tree — holding the indexed columns plus a pointer to the row (the primary key). It turns a full scan into a tree search: O(log n) page reads instead of reading every row, and it also gives you rows in sorted order for free, which helps ORDER BY, GROUP BY and range filters. The costs are disk and memory space, and write amplification: every insert, delete and update of an indexed column has to change every affected index. So you index for the queries you actually run, prefer one good composite index over several single-column ones, and drop indexes nothing uses.

Open in topic →

Why B+trees and not binary trees or hash tables?

Show answer

Databases read storage in pages, so the goal is the fewest page reads. A B+tree puts hundreds of keys in each node, so it's only three or four levels deep even for hundreds of millions of rows — three or four page reads per lookup, and the top levels are always cached. Only the leaves hold entries, and the leaves are linked, so a range or an ORDER BY is one descent plus a sequential walk. A binary tree would be about 30 levels deep with one key per node; a hash table finds single keys fast but can't do ranges or ordering.

Open in topic →

What's the difference between a clustered and a secondary index?

Show answer

In InnoDB the clustered index is the table: the primary key's B+tree, with full rows stored in its leaves in key order, so there's exactly one per table. A secondary index is a separate B+tree on other columns whose leaves store the indexed values plus the primary key. Looking up a row through a secondary index means searching it, then searching the clustered index by primary key — unless the index covers the query. That's why you keep primary keys short and increasing: they're copied into every secondary index, and sequential keys append to the end of the clustered index instead of splitting pages.

Open in topic →

How do you choose the column order in a composite index?

Show answer

Start from the queries. Columns compared with = go first, then the column used for a range or for ORDER BY, because only one range can be used for seeking and anything after it can only be filtered. Among the equality columns, the most-queried one goes first so more queries can use the prefix. Then check whether adding the selected columns makes it covering. And remember an index on (a, b) also serves queries on a alone, so a separate index on a is redundant.

Open in topic →

Which queries can use the index?

The table has INDEX idx (a, b, c). Which of these can use the index to seek, and on how many columns?

  1. WHERE a = 1 AND c = 3
  2. WHERE b = 2 AND a = 1
  3. WHERE a > 1 AND b = 2
  4. WHERE b = 2 AND c = 3
Show answer
  1. Seeks on a only; c is checked inside the index (index condition pushdown) because b is missing between them.
  2. Seeks on a and b. The order of conditions in WHERE doesn't matter — the optimizer matches columns, not text.
  3. Seeks on a only, as a range. Once a is a range, the b values inside it aren't sorted, so b can only be filtered.
  4. Can't seek at all: no condition on a. At best a full index scan (if the index covers the query) or a skip scan (if a has very few distinct values).
What’s happening
  1. Picture the entries sorted by a, then b, then c.
  2. For each query, find the longest run of leading columns with = conditions, plus at most one more column used as a range. That's the seek prefix.
  3. Query 1: the prefix is a, then b is missing → stop. Query 2: a and b are both =. Query 3: a is a range → stop after it. Query 4: no a → no prefix.
Open in topic →

What is a covering index?

Show answer

An index that contains every column a query needs, so the database answers from the index and never reads the table rows. In InnoDB that saves one primary-key lookup per matching row, which for big ranges is most of the cost; EXPLAIN shows Using index. Remember that the primary key is implicitly in every secondary index, so (customer_id, total) covers SELECT id, total WHERE customer_id = ?. The trade-off is a wider index and more write cost, so you build them for hot queries, not everywhere.

Open in topic →

Why might MySQL ignore an index on a column that's in the WHERE clause?

Show answer

Usually because it estimates that too many rows match. Every row found through a secondary index costs a random lookup into the clustered index, and beyond a certain fraction of the table a sequential scan is cheaper, so on a low-cardinality column like status the scan is often right. The opposite happens too: estimates come from sampled statistics, and when they're off the optimizer can use an index that's slower than a scan — on this 500,000-row table it used an index for a value that matches 70 % of the rows and took 141 ms where a scan took 62 ms. You check with EXPLAIN ANALYZE, refresh statistics with ANALYZE TABLE, add histograms for non-indexed columns, and use better composite indexes or hints as a last resort.

Open in topic →

Read this plan

Output
+----+-------------+-------+------+---------------+------+---------+------+-------+----------+-----------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows  | filtered | Extra                       |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------+-----------------------------+
|  1 | SIMPLE      | o     | ALL  | NULL          | NULL | NULL    | NULL | 80000 |    10.00 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+-------+----------+-----------------------------+

What is MySQL doing, and what's the first thing you'd check?

Show answer

It's a full table scan of o (80,000 rows), keeping an estimated 10 % with the WHERE condition, then sorting what's left for the ORDER BY. possible_keys: NULL means no index is even usable for the conditions — so first check the WHERE columns: is there an index whose leftmost column is filtered, and is the column used bare (not wrapped in a function or compared with a different type)?

What’s happening
  1. type: ALL + key: NULL → no index used; every row is read.
  2. possible_keys: NULL → not a cost decision: no index matched at all. (If indexes were listed but key was NULL, the optimizer would have rejected them as too expensive — the selectivity case.)
  3. filtered: 10.00 → a fixed guess for an equality with no statistics: the optimizer doesn't know the distribution.
  4. Using filesort → the rows are sorted after filtering. An index that serves both the filter and the order (equality columns, then the sort column) would remove both the scan and the sort.
Open in topic →

What's the difference between EXPLAIN and EXPLAIN ANALYZE?

Show answer

EXPLAIN shows the plan the optimizer intends to use with its estimated costs and row counts, without running anything — instant and safe. EXPLAIN ANALYZE actually executes the query and annotates each step with real time to first and last row, real rows and loop counts, so you can see where the time went and where the estimates were wrong. A big gap between estimated and actual rows on a node is usually the root cause of a bad plan. Because it runs the query, it takes as long as the query and must be handled carefully with anything that writes.

Open in topic →

Spot the slow query

Both queries return the orders placed in 2025. One is fast and one is slow on a large table with an index on ordered_at. Which is which, and why?

SQL
SELECT id FROM big_orders WHERE YEAR(ordered_at) = 2025;
SELECT id FROM big_orders WHERE ordered_at >= '2025-01-01' AND ordered_at < '2026-01-01';
Show answer

The first is slow: YEAR(ordered_at) hides the column inside a function, so the index can't be searched — the plan is a scan of the entire index with year(…) evaluated for every entry, as with DATE() above. The second compares the bare column with constants and can be a range scan.

What’s happening
  1. The index is sorted by ordered_at. "Rows where YEAR(ordered_at) is 2025" isn't a position in that order, unless MySQL knows YEAR() is monotonic — it doesn't reason that way.
  2. The second query states the same set as a range of raw values: seek to 2025-01-01, stop before 2026-01-01.
  3. One caveat: 2025 is about a third of this table, so the optimizer may still prefer a full scan for the second query (WHERE ordered_at >= '2024-01-01', two thirds of the rows, got a Table scan here). Sargable makes the index possible; selectivity decides whether it's worth it.
Open in topic →

How would you paginate a large table efficiently?

Show answer

With keyset pagination: sort by an indexed, unique key — or a sort column plus the primary key as a tie-breaker — and fetch the next page with WHERE (sort_col, id) is after the last row seen ORDER BY sort_col, id LIMIT n. Each page is an index seek plus n rows, so page 10,000 costs the same as page 1, and pages don't drift when rows are inserted. OFFSET has to read and discard every skipped row, so it gets linearly slower; on 500,000 rows offset 400,000 took 32 ms against 0.2 ms with a keyset. The trade-off is no random access to page numbers; if you need those, cap the depth or use a deferred join on a covering index.

Open in topic →

Predict the cost

Each page holds 50 rows. Roughly how many index entries does MySQL read to serve page 1,000 with ORDER BY id LIMIT 50 OFFSET 49950, and with WHERE id > :last_id ORDER BY id LIMIT 50?

Show answer

About 50,000 entries for the OFFSET version (49,950 skipped + 50 returned), and about 50 for the keyset version.

What’s happening
  1. OFFSET can't skip ahead in a B+tree: there are no row numbers in the index, so MySQL walks 49,950 entries just to count them, then returns the next 50.
  2. Keyset seeks to :last_id (three or four page reads for the descent) and reads the next 50 entries.
  3. Doubling the page number doubles the OFFSET cost; the keyset cost stays the same.
Open in topic →

A query is slow in production. How do you investigate?

Show answer

First find out whether it's the query or the system: check the slow log or performance_schema digests for its time, rows examined and rows sent, and whether it's always slow or only under load (lock waits show up as high lock time and in sys.innodb_lock_waits). Then run EXPLAIN — and EXPLAIN ANALYZE on a replica or a copy — and look for full scans, filesorts and temporary tables on big row counts, and for estimates far from actual rows. The usual fixes are an index that matches the filter and sort (equality columns first, then range or sort, ideally covering), making the condition sargable, refreshing statistics, or rewriting OFFSET pagination as keyset. Then measure again, and check the fix didn't hurt writes.

Open in topic →

Explain ACID.

Show answer

Atomicity: a transaction's changes happen all together or not at all — InnoDB records undo information for every change and rolls it back on ROLLBACK or crash recovery. Consistency: each transaction takes the database from one valid state to another, which is the constraints the database enforces plus the invariants your transactions maintain. Isolation: concurrent transactions don't see each other's uncommitted work; InnoDB does that with MVCC snapshots for reads and locks for writes, and the isolation level decides how strict it is. Durability: once commit returns, the data survives a crash, because the redo log is flushed to disk at commit. One MySQL-specific detail worth mentioning: a failed statement only rolls back itself, so the application must roll back the transaction.

Open in topic →

What does the table contain?

SQL
START TRANSACTION;
INSERT INTO accounts VALUES (4, 'Sofia', 50.00);
SAVEPOINT a;
INSERT INTO accounts VALUES (5, 'Noah', 70.00);
SAVEPOINT b;
INSERT INTO accounts VALUES (6, 'Zara', 90.00);
ROLLBACK TO SAVEPOINT a;
INSERT INTO accounts VALUES (7, 'Asha', 30.00);
COMMIT;

Which of the rows 4–7 exist afterwards?

Show answer

Rows 4 and 7.

What’s happening
  1. Row 4 is inserted before savepoint a, so no rollback in this transaction can touch it except a full ROLLBACK.
  2. Rows 5 and 6 were inserted after a; ROLLBACK TO SAVEPOINT a undoes both. It also deletes savepoint b, because b was set after a.
  3. The transaction is still open, so row 7 is inserted normally, and COMMIT keeps 4 and 7.
Open in topic →

What is autocommit, and what are implicit commits?

Show answer

With autocommit on, MySQL's default, every statement outside an explicit transaction commits as soon as it succeeds. START TRANSACTION suspends that until COMMIT or ROLLBACK, and SET autocommit = 0 makes the session always be inside a transaction, so you must commit explicitly. Implicit commits are statements that commit the current transaction for you: all DDL, LOCK TABLES, user management and even another START TRANSACTION. The practical consequences are that you can't roll back DDL in MySQL, unlike PostgreSQL, and that a session with autocommit off that forgets to commit holds its locks indefinitely.

Open in topic →

What isolation levels are there, and which does MySQL use?

Show answer

Four: read uncommitted allows dirty reads; read committed only shows committed data but each statement can see newer commits, so reads aren't repeatable; repeatable read gives the whole transaction one consistent snapshot; serializable makes concurrent transactions behave as if they ran one after another. InnoDB's default is repeatable read, implemented with MVCC: a plain select reads from a snapshot taken at the first read, without locking. Unlike the textbook definition, InnoDB's repeatable read also prevents phantoms for plain reads, and uses next-key locks for locking reads. PostgreSQL and SQL Server default to read committed, and many MySQL shops switch to it to reduce gap-lock contention.

Open in topic →

Predict the count

Under InnoDB's default REPEATABLE READ:

SQL
-- Session A
START TRANSACTION;
SELECT COUNT(*) FROM accounts;            -- returns 3
-- Session B (autocommit)
INSERT INTO accounts VALUES (4, 'Sofia', 250.00);
-- Session A
SELECT COUNT(*) FROM accounts;            -- (1) ?
SELECT COUNT(*) FROM accounts FOR SHARE;  -- (2) ?
SELECT COUNT(*) FROM accounts;            -- (3) ?
Show answer

(1) 3, (2) 4, (3) 3.

What’s happening
  1. (1) is a plain consistent read from A's snapshot, taken at A's first SELECT, before Sofia existed.
  2. (2) is a locking read. Locking reads ignore the snapshot and read the latest committed rows (and lock them), so they see Sofia.
  3. (3) is a plain read again, back to the snapshot: 3. The same transaction can see two different "truths" depending on how it reads — the same effect the MVCC example below shows with FOR SHARE on a single row.
Open in topic →

What's a phantom read, and does MySQL prevent it?

Show answer

A phantom is when the same query, run twice in one transaction, returns a different set of rows because another transaction inserted or deleted matching rows and committed in between. The SQL standard allows phantoms at repeatable read, but InnoDB prevents them for plain selects because the whole transaction reads one MVCC snapshot. For locking reads and writes, which always read the latest data, it prevents them with next-key and gap locks that stop other transactions inserting into the scanned range. The caveat is that mixing the two — a snapshot read followed by an update — can still let new rows in, so for check-then-write logic you use SELECT … FOR UPDATE.

Open in topic →

How does MVCC work in InnoDB?

Show answer

Each update writes the new row version in place and moves the old version into the undo log, linked by a roll pointer, and every version records the transaction id that created it. A consistent read uses a read view — essentially the set of transactions that were committed when the snapshot was taken — and follows each row's version chain back to the newest version it's allowed to see, so readers never wait for writers. In repeatable read the read view is created at the first read and kept for the whole transaction; in read committed a new one is created for each statement. Writes and locking reads ignore the snapshot and operate on the latest committed version with locks. Old versions are purged once no read view needs them, which is why a long-running transaction makes the undo log grow.

Open in topic →

When would you use SELECT … FOR UPDATE?

Show answer

When a transaction reads a row in order to decide how to change it — check stock then decrement, check a balance then debit, read a counter then write the next value. FOR UPDATE reads the latest committed version and takes an exclusive lock, so any other transaction doing the same waits until you commit, which prevents lost updates and write skew on those rows. It only works inside a transaction, it should be on an indexed condition because InnoDB locks every index record it scans, and the transaction should be short. If the change can be expressed as a single atomic statement like UPDATE … SET stock = stock - 1 WHERE id = ? AND stock > 0, that's better still.

Open in topic →

Which statements wait?

gap_demo holds ids 10, 20 and 30 (primary key). Session A, in REPEATABLE READ, runs START TRANSACTION; SELECT * FROM gap_demo WHERE id BETWEEN 15 AND 25 FOR UPDATE; and stays open. Which of these, run by session B, have to wait?

  1. INSERT INTO gap_demo VALUES (17, 'x');
  2. INSERT INTO gap_demo VALUES (27, 'x');
  3. INSERT INTO gap_demo VALUES (35, 'x');
  4. UPDATE gap_demo SET note = 'TEN' WHERE id = 10;
Show answer

Only 1 and 2 wait; 3 and 4 run immediately — exactly what the example above showed.

What’s happening
  1. A's scan locked the next-key (10, 20] on record 20 and the gap (20, 30) before record 30: everything strictly between 10 and 30.
  2. 17 falls in (10, 20) and 27 in (20, 30), so both inserts need an insert-intention lock in a locked gap and wait. 27 is outside A's WHERE, but gaps are locked whole.
  3. 35 falls in the gap after 30, which nobody locked, so it inserts at once.
  4. Row 10 is the left boundary of a locked gap, but its own record isn't locked, so the update goes through.
Open in topic →

What are gap locks and next-key locks?

Show answer

InnoDB locks index records, and in repeatable read it also locks the gaps between them so that other transactions can't insert rows into a range you've read with a locking read — that's how it prevents phantoms. A gap lock covers the open interval before a record and only blocks inserts; gap locks don't conflict with each other. A next-key lock is a record lock plus the gap before it, and it's the default for locking scans. For example, BETWEEN 15 AND 25 FOR UPDATE on ids 10, 20, 30 locked the gap from 10 to 30, so inserting 27 also waited. An equality lookup on a unique index takes just a record lock. Read committed mostly disables gap locking, which is why it has fewer lock waits and deadlocks.

Open in topic →

How do you handle deadlocks?

Show answer

First, accept that they happen: InnoDB detects the cycle immediately, rolls back one transaction and returns error 1213, so the application has to catch that error and retry the whole transaction, with a cap and a small back-off. Then reduce them: access rows in a consistent order, keep transactions short, make sure updates and locking reads use indexes so fewer records are locked, and consider read committed if gap locks are involved. To diagnose, look at LATEST DETECTED DEADLOCK in SHOW ENGINE INNODB STATUS, or turn on innodb_print_all_deadlocks to log every one: it shows both statements, which locks each held and which each waited for.

Open in topic →

How would you build a job queue on MySQL?

Show answer

A jobs table with a status and an index on (status, id). Each worker, in a short transaction, runs SELECT … WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED, marks the row as claimed with its worker id and a timestamp, and commits; it then does the work outside the transaction and marks the job done. SKIP LOCKED makes concurrent workers skip rows another worker has locked instead of queueing behind it, so they never block each other or take the same job. For robustness you re-queue jobs whose claim is too old. Before MySQL 8.0 you'd have needed an atomic UPDATE … LIMIT 1 with a claim token, since there was no SKIP LOCKED.

Open in topic →

Optimistic vs pessimistic locking — when do you use which?

Show answer

Pessimistic locking takes the lock up front with SELECT … FOR UPDATE, so competing transactions wait; it's right when conflicts are likely and the read-modify-write happens in one short transaction. Optimistic locking takes no locks: you keep a version column, update with WHERE id = ? AND version = ?, and treat zero affected rows as a conflict to retry or report; it's right when conflicts are rare or the read and the write are far apart, like an edit form, because nothing is held while the user thinks. Under heavy contention on one row optimistic locking wastes work on retries — in a test with 50 buyers on one product it needed around 200 retries — and for simple counters a single atomic UPDATE … SET stock = stock - 1 WHERE stock > 0 beats both.

Open in topic →

A view built with SELECT *

SQL
CREATE TABLE notes (id INT PRIMARY KEY, body VARCHAR(50));
INSERT INTO notes VALUES (1, 'hello');
CREATE VIEW all_notes AS SELECT * FROM notes;
ALTER TABLE notes ADD COLUMN author VARCHAR(20) DEFAULT 'rohit';
SELECT * FROM all_notes;

Does the result include author? What happens if you then drop body from the table?

Show answer

No author column, and after dropping body the view is broken. The question's statements, then these three:

SQL
SELECT VIEW_DEFINITION FROM information_schema.VIEWS WHERE TABLE_NAME = 'all_notes';
ALTER TABLE notes DROP COLUMN body;
SELECT * FROM all_notes;
Result
+----+-------+
| id | body  |
+----+-------+
|  1 | hello |
+----+-------+
+----------------------------------------------------------------------------------------+
| VIEW_DEFINITION                                                                        |
+----------------------------------------------------------------------------------------+
| select `ch11`.`notes`.`id` AS `id`,`ch11`.`notes`.`body` AS `body` from `ch11`.`notes` |
+----------------------------------------------------------------------------------------+
ERROR 1356 (HY000): View 'ch11.all_notes' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
What’s happening
  1. When CREATE VIEW runs, MySQL expands * into the columns that exist at that moment and stores the expanded list. information_schema.VIEWS.VIEW_DEFINITION shows it: id and body, spelled out.
  2. ALTER TABLE … ADD COLUMN author changes the table, not the stored view text, so SELECT * FROM all_notes still returns only id and body.
  3. ALTER TABLE notes DROP COLUMN body succeeds — MySQL doesn't check which views use a column — and the next query on the view fails with ERROR 1356. The break shows up at query time, often in production.
  4. The lesson: list columns explicitly in views, recreate views (CREATE OR REPLACE VIEW) in the same migration that changes their tables, and search information_schema.VIEWS before dropping a column.
Open in topic →
InterviewCh 11 Views

What is a view, and does it make queries faster?

Show answer

A view is a stored SELECT with a name. It holds no data; every query against it runs the stored query on the base tables, so it's always current. I use views to name a complicated join, to give consumers a stable interface while tables change, and for security, because I can grant SELECT on a view that hides columns or rows without granting the base tables. It doesn't make anything faster by itself: a simple view is merged into the outer query and costs nothing, and a view with GROUP BY or DISTINCT is materialised into a temporary table each time it's used, which can be slower than a hand-written query. MySQL has no materialized views; if I need a precomputed result I keep a summary table and refresh it with a scheduled event or triggers, or use PostgreSQL's MATERIALIZED VIEW. Simple single-table views are updatable, and WITH CHECK OPTION stops writes through the view from creating rows the view can't see.

Open in topic →

Should business logic live in stored procedures?

Show answer

Usually not all of it. Procedures run next to the data, so a multi-statement operation costs one round trip, and every client gets the same rule. But they're written in a limited language, hard to unit-test, debug, review and version alongside the application, they scale only as far as the one database server, and they lock you to one vendor. I keep core business rules in the application, with constraints, foreign keys and transactions in the database guaranteeing integrity, and I use procedures for specific jobs: batch maintenance like purging in chunks, data migrations and fixes, or a chatty sequence where round trips really matter. When I do write one, it handles errors with an EXIT HANDLER that rolls back and RESIGNALs, and it lives in version control with the migrations.

Open in topic →

What's the difference between a stored procedure and a function?

Show answer

A function returns a single value and is used inside expressions — SELECT with_tax(total, 13) — so it can't return result sets, run transactions or use dynamic SQL, and with binary logging on I must declare whether it's DETERMINISTIC, NO SQL or READS SQL DATA. A procedure is called with CALL, returns data through OUT parameters and any number of result sets, and can control transactions. The performance point people miss is that a function in a WHERE or SELECT list runs once per row, and if it queries a table that's a hidden N+1 inside the server that also blocks index use, so I keep functions small and pure and write joins for anything set-based.

Open in topic →

Do cascades fire triggers?

cart_items has FOREIGN KEY (cart_id) REFERENCES carts(id) ON DELETE CASCADE, and both tables have an AFTER DELETE trigger that writes a line to deleted_log:

Starting dataThe carts, their items and the two triggers
SQL
CREATE TABLE carts (id INT PRIMARY KEY, owner VARCHAR(20));
CREATE TABLE cart_items (
  cart_id INT, sku VARCHAR(10), PRIMARY KEY (cart_id, sku),
  FOREIGN KEY (cart_id) REFERENCES carts(id) ON DELETE CASCADE
);
CREATE TABLE deleted_log (what VARCHAR(40));
CREATE TRIGGER carts_ad AFTER DELETE ON carts FOR EACH ROW
  INSERT INTO deleted_log VALUES (CONCAT('cart ', OLD.id));
CREATE TRIGGER cart_items_ad AFTER DELETE ON cart_items FOR EACH ROW
  INSERT INTO deleted_log VALUES (CONCAT('item ', OLD.cart_id, '/', OLD.sku));
SQL
INSERT INTO carts VALUES (1, 'rohit');
INSERT INTO cart_items VALUES (1, 'A'), (1, 'B');
DELETE FROM carts WHERE id = 1;
SELECT (SELECT COUNT(*) FROM cart_items) AS items_left, what FROM deleted_log;

How many lines are in deleted_log?

Show answer

One. The two cascaded item deletes don't fire the cart_items trigger.

Result
+------------+--------+
| items_left | what   |
+------------+--------+
|          0 | cart 1 |
+------------+--------+
What’s happening
  1. DELETE FROM carts WHERE id = 1 deletes the cart row and fires carts_ad, which logs cart 1.
  2. InnoDB then applies ON DELETE CASCADE and deletes both items: items_left is 0.
  3. But cascades are performed inside the storage engine, below the SQL layer where triggers run, and MySQL documents that cascaded foreign key actions do not activate triggers. cart_items_ad never fires, so item 1/A and item 1/B are not logged.
  4. Deleting an item directly (DELETE FROM cart_items WHERE cart_id = 2) does fire it, and logs item 2/C. TRUNCATE TABLE doesn't fire DELETE triggers either (it drops and recreates the table): after a TRUNCATE, the log count stayed 0.
  5. If an audit trail must cover children, either delete the children explicitly in application code or a procedure before the parent, or put the logging on the parent. PostgreSQL implements cascades as internal triggers, so there the child triggers do fire — a real difference between the two.
Open in topic →

What are triggers, and what are their drawbacks?

Show answer

A trigger is code that runs automatically before or after an insert, update or delete on a table, once per row in MySQL, with OLD and NEW giving the row before and after. It runs in the same transaction, so an error in it rolls back the statement. I use them for audit and history tables, for normalising data in a BEFORE trigger, and occasionally to maintain a summary. The drawbacks: they're invisible from application code, they slow every write, they can't modify their own table (error 1442), they don't fire for foreign key cascades or TRUNCATE in MySQL, debugging chains of them is painful, and tools like gh-ost won't run on tables that have them. So I keep them small, few and documented.

Open in topic →

How would you run a nightly cleanup job in MySQL?

Show answer

I'd either use a scheduled event — CREATE EVENT … ON SCHEDULE EVERY 1 DAY STARTS '…03:00' calling a procedure that deletes in batches — or an external scheduler that calls the same procedure. The event scheduler is on by default since 8.0 and keeps the job next to the data, but its failures only go to the error log and it runs only on the source, so after a failover the events must be re-enabled on the new source. Either way the job deletes in small batches so it doesn't hold long locks or lag replicas, writes a status row to a job-log table, and is monitored for "no success in 25 hours".

Open in topic →

The role that does nothing

SQL
CREATE USER 'ch11_temp'@'%' IDENTIFIED BY 'Temp-pass-123';
GRANT ch11_reader TO 'ch11_temp'@'%';

ch11_temp logs in and runs SELECT COUNT(*) FROM ch11.orders. What happens?

Show answer

It's denied. A granted role isn't active until it's set as a default role or activated with SET ROLE. Logged in as ch11_temp (mysql -h 127.0.0.1 -u ch11_temp -p):

SQL
SELECT CURRENT_ROLE();
SELECT COUNT(*) FROM ch11.orders;
SET ROLE ch11_reader;
SELECT COUNT(*) FROM ch11.orders;
Result
+----------------+
| CURRENT_ROLE() |
+----------------+
| NONE           |
+----------------+
ERROR 1142 (42000): SELECT command denied to user 'ch11_temp'@'127.0.0.1' for table 'orders'
+----------+
| COUNT(*) |
+----------+
|        8 |
+----------+
What’s happening
  1. GRANT ch11_reader TO 'ch11_temp'@'%' lets the user use the role, but MySQL starts each session with only the account's default roles active, and this account has none.
  2. CURRENT_ROLE() prints NONE, and the SELECT fails with ERROR 1142, exactly as if the role had never been granted. This surprises everyone the first time.
  3. After SET ROLE ch11_reader in the session, the same SELECT returns 8.
  4. The permanent fixes: SET DEFAULT ROLE ch11_reader TO 'ch11_temp'@'%' (or DEFAULT ROLE in CREATE USER, as for ch11_app), or the server setting activate_all_roles_on_login = ON, which activates every granted role at login.
Open in topic →

How do you secure the database account an application uses?

Show answer

I give each application its own account, restricted by host where the network allows, with a strong password stored in a secrets manager and rotated (MySQL 8.0.14+ supports dual passwords with RETAIN CURRENT PASSWORD for zero-downtime rotation). It gets only the privileges it uses — usually SELECT, INSERT, UPDATE, DELETE on its own schema, through a role — and never DROP, GRANT, FILE or SUPER. Migrations run with a separate, more privileged account. Read-only consumers get a reader role, sensitive columns are exposed through views or column grants, and connections require TLS. Remember that roles must be default or activated with SET ROLE, and that since 8.0 you must CREATE USER before GRANT.

Open in topic →

ORDER BY ?

SQL
PREPARE bad FROM 'SELECT id, name FROM customers ORDER BY ?';
SET @col = 'name';
EXECUTE bad USING @col;

Are the customers sorted by name?

Show answer

No. They come back in whatever order MySQL reads them — here, by id.

Result
+----+-------+
| id | name  |
+----+-------+
|  1 | Rohit |
|  2 | Maya  |
|  3 | Liam  |
|  4 | Sofia |
|  5 | Noah  |
|  6 | Zara  |
+----+-------+
What’s happening
  1. A placeholder always stands for a value, never an identifier. So ORDER BY ? with 'name' means "order by the string constant 'name'", the same for every row.
  2. Sorting by a constant doesn't reorder anything, and MySQL returns rows in primary-key order because that's how it scanned the table. No error, no warning: a silent bug.
  3. Placeholders in the table position fail loudly instead: PREPARE bad2 FROM 'SELECT id, name FROM ? LIMIT 1' gives ERROR 1064 (42000): You have an error in your SQL syntax … near '? LIMIT 1'.
  4. Table names, column names, ASC/DESC and other keywords must come from an allowlist in your code (map the user's choice to a known identifier), as in products_sorted.
Open in topic →

How do prepared statements prevent SQL injection?

Show answer

SQL injection works because the server parses a string that mixes my SQL with the user's input, so input containing quotes or keywords changes the query's structure. A prepared statement separates the two: the SQL with ? placeholders is parsed and planned first, and the values are sent afterwards and bound as data, so they can never become syntax — ' OR '1'='1 is just a strange email address. Parameters only cover values, though: identifiers like sort columns must be allowlisted, LIKE wildcards escaped, and dynamic SQL inside stored procedures needs the same discipline, EXECUTE … USING for values and an allowlist for anything else. On top of that, least-privilege accounts limit the damage if something slips through.

Open in topic →

How do you protect sensitive data in MySQL?

Show answer

In layers. In transit, TLS on every connection — require_secure_transport = ON or REQUIRE SSL per account — and clients verify the server certificate. At rest, InnoDB tablespace encryption with a keyring backed by a KMS, plus binlog, redo and undo log encryption and encrypted backups; that protects against stolen disks and files but not against SQL users. For the most sensitive fields I encrypt in the application with keys from a KMS, so the database only stores ciphertext and keys never appear in SQL text or logs, with a keyed hash column if I need lookups. Access is least-privilege with roles, views and column grants. And for auditing I use an audit plugin or the cloud provider's audit log — Enterprise Audit isn't in Community MySQL — rather than the general query log, which is too heavy and records secrets in plain text.

Open in topic →

How would you scale a MySQL database that's struggling?

Show answer

First I'd find out what it's struggling with: slow queries, CPU, I/O, lock waits or connection count. Most problems are fixed by indexes and query changes, and by giving the buffer pool enough RAM that the hot data is served from memory. Then I'd scale vertically, because it changes nothing in the application. For read-heavy load I'd add read replicas and route reads that can tolerate a little staleness to them, keeping read-your-writes paths on the primary, plus a cache like Redis for hot data. Writes don't scale with replicas, because every replica applies every write, so when one primary can't take the write volume the options are splitting the data by function into separate databases, or sharding by a key such as tenant or customer ID, usually with tooling like Vitess or a distributed SQL database rather than hand-rolled routing.

Open in topic →

How does MySQL replication work?

Show answer

The source writes every committed transaction to its binary log, by default in row format — the before and after images of each changed row — and each transaction has a GTID. A replica connects as a replication user; its receiver thread streams new binlog events into a local relay log, and applier threads, several in parallel, replay them in commit order. With GTID auto-positioning the replica just tells the source which transactions it already has. By default it's asynchronous: the source commits without waiting for replicas, so replicas lag slightly and a crash of the source can lose the last few transactions. I make replicas super_read_only, make sure every table has a primary key, and monitor that both threads are running and the lag. Replicas are for read scaling and failover, not backups, because they replicate mistakes too.

Open in topic →

What's the difference between async and semi-sync replication?

Show answer

With async replication the source commits and returns to the client without waiting for any replica, so replicas lag a little and if the source crashes, transactions it committed but hadn't yet sent are lost when you fail over. With semi-sync, the source waits until at least one replica acknowledges it has received the transaction into its relay log — not applied it — before returning, so a failover to that replica doesn't lose committed data, at the cost of one round trip per commit. MySQL's default AFTER_SYNC wait point makes it lossless, because the transaction isn't visible to anyone before the acknowledgement. The catch is the timeout: if no replica answers within rpl_semi_sync_source_timeout, the source silently falls back to async, which I showed in a test as one 3-second commit and then status OFF, so it has to be monitored. Group Replication goes further with majority consensus and automatic failover.

Open in topic →

How do you handle replication lag with read replicas?

Show answer

I treat every replica read as possibly stale and decide per query whether that's acceptable. Lists, search and dashboards go to replicas; anything that must reflect the user's own write — the page after a save, a balance check before a payment — goes to the primary, either always or for a few seconds after that user writes, or I wait on the replica for the GTID of the write with WAIT_FOR_EXECUTED_GTID_SET. Read-modify-write logic and transactions never touch replicas. On the operations side I keep transactions small so replicas don't stall on one huge change, monitor lag with a heartbeat table rather than trusting Seconds_Behind_Source, and take a lagging replica out of the read pool automatically.

Open in topic →

What is partitioning and when would you use it?

Show answer

Partitioning splits one table into physical pieces on the same server by a rule on a column — usually date ranges — while queries still see one table. The optimizer prunes partitions a query can't need, but only when the query filters on the partitioning column. In MySQL its main value is lifecycle management: dropping a month of old data with DROP PARTITION takes milliseconds instead of a long, replica-lagging DELETE. The costs are that every unique key must include the partitioning column, partitioned tables can't have foreign keys, and queries that don't filter on that column get slightly slower. It doesn't add capacity, because everything is still on one server; that's sharding.

Open in topic →

How would you shard a MySQL database?

Show answer

I'd only do it once a single primary, scaled up, with replicas and caching, can't take the write volume or the data size. The key decision is the shard key: something nearly every query includes, like tenant or customer ID, with high cardinality and no single giant value, so most requests hit one shard and data spreads evenly. I'd route through a bucket directory or consistent hashing rather than id % N, so adding shards moves only the minimum data — modulo going from 2 to 3 shards moves two thirds of rows. IDs must be globally unique without coordination, so UUIDv7 or Snowflake-style IDs instead of auto-increment. And I'd plan for what's lost: cross-shard joins and transactions, global uniqueness and reporting, which usually moves to a separate analytics store. In practice I'd use Vitess or a distributed SQL database rather than writing the routing myself.

Open in topic →

Why do we need connection pooling?

Show answer

Opening a MySQL connection costs several network round trips plus TLS and authentication, and each connection is a server thread with its own memory, capped by max_connections. A pool keeps a small set of connections open and lends them out per query or transaction, so requests skip the setup cost and the total number of connections stays bounded — requests queue in the pool instead of overwhelming the server. The sizing rule is that total connections are instances times pool size, which must stay under max_connections with headroom, and that more active connections than the server can run in parallel only adds contention. When there are too many clients — lots of pods, or serverless functions — I put a proxy like ProxySQL or RDS Proxy in front to multiplex them. And I configure idle timeouts below the server's wait_timeout so the pool never hands out a dead connection.

Open in topic →

How do you back up MySQL and recover from an accidental DELETE?

Show answer

I combine full backups with continuous binary logs. For small databases a nightly mysqldump --single-transaction or MySQL Shell dump is fine; for large ones a physical backup with XtraBackup, the clone plugin or storage snapshots, because restoring a logical dump of hundreds of gigabytes takes hours. The binlog is kept and copied off the server continuously. To recover from a bad DELETE or UPDATE, I restore the latest backup onto a separate server, find the bad transaction in the binlog with mysqlbinlog by time or table, and replay the binlog from the backup's recorded position either up to just before it or, with GTIDs, skipping just that transaction with --exclude-gtids. Then I verify and either copy the affected tables back or cut over. A delayed replica can make this much faster, replicas themselves are not backups, and restores are tested regularly.

Open in topic →

Walk me through a database failover.

Show answer

Detection first: health checks from more than one place decide the primary is really down, not just unreachable from one monitor. Then fencing, so the old primary can't take writes if it comes back. Then choose the most up-to-date replica by comparing GTID sets, let it finish applying its relay log, stop replication on it, reset its replication config and turn off read_only and super_read_only. Point the application at it through DNS, a VIP or a proxy, and re-point the other replicas with GTID auto-positioning. With async replication anything the old primary committed but hadn't shipped is lost — I showed this with a confirmed order that vanished — so for zero loss I'd use semi-sync or Group Replication. The old primary never rejoins as-is: it may have errant transactions, so it's rebuilt, for example with CLONE INSTANCE, and its extra transactions reconciled by hand. In practice InnoDB Cluster, Orchestrator or a managed service's Multi-AZ does the automation.

Open in topic →

How do you put a cache in front of MySQL, and what can go wrong?

Show answer

I'd use cache-aside with Redis: read from the cache, on a miss query MySQL and store the result with a TTL, and on writes update MySQL and then delete the key. It helps most for expensive, frequently repeated queries — in a test, a 50 ms report became 0.1 ms — and it takes read load off the database; for cheap indexed lookups the gain is mostly load, not latency. What goes wrong: stale data when some write path forgets to invalidate, so I keep TTLs short and invalidate in one place; stampedes when a hot key expires, handled with a lock or early refresh; serialisation changing types, like dates coming back as strings; and caching things that must be exact, like stock at checkout. MySQL's own query cache was removed in 8.0, so this is application-level now.

Open in topic →

Why use a connection pool in a Node application?

Show answer

Because a MySQL connection is expensive to open — TCP, authentication and TLS handshakes, several round trips — and each one is a thread on the server, capped by max_connections. In a test, opening a TLS connection per query cost about 1.9 ms against 0.12 ms through a pool, on localhost. I create one pool per process at startup, with a connectionLimit sized so instances × limit stays well under the server's limit, and let requests queue in the pool. Independent queries use pool.query(); transactions use pool.getConnection() so every statement runs on the same connection, released in finally. I also watch for session state leaking between borrowers, and close the pool on shutdown.

Open in topic →

What's the difference between query() and execute() in mysql2?

Show answer

query() escapes the values in the driver and sends one text query, so the server sees literals; execute() uses a server-side prepared statement over the binary protocol, preparing the SQL once per connection and then sending only values. Both protect against injection for values. The practical differences are that execute() saves parsing for repeated queries but needs a fixed SQL shape — an array in IN (?) gets bound as a single string and silently matches nothing, so you generate one placeholder per element — while query() supports array expansion and ?? identifiers. And whichever you use, DECIMAL comes back as a string, dates are converted in the process's time zone, and multipleStatements should stay off.

Open in topic →

Where did B's update go?

Two requests share one pool. Request A sends its transaction through pool.query(); request B, meanwhile, runs one ordinary auto-committed update:

begin-on-pool.mjs
// The classic bug: START TRANSACTION / UPDATE / ROLLBACK sent through pool.query().
import mysql from "mysql2/promise";
import { setTimeout as sleep } from "node:timers/promises";

const pool = mysql.createPool({ host: "127.0.0.1", port: 3307, user: "root", password: "study", database: "ch11_orm", connectionLimit: 3 });
let lastConnection;
pool.pool.on("acquire", (conn) => { lastConnection = conn.threadId; });          // which connection ran the last call?
const q = async (who, sql, params) => {
  await pool.query(sql, params);
  console.log(`${who}: ${sql.padEnd(52)} on connection ${lastConnection}`);
};
const stock = async () => (await pool.query("SELECT stock FROM products WHERE id = 5"))[0][0].stock;

await pool.query("UPDATE products SET stock = 50 WHERE id = 5");

async function requestA() {                       // a "transaction" that changes its mind
  await q("A", "START TRANSACTION");
  await sleep(20);                                // e.g. calling a payment API
  await q("A", "UPDATE products SET stock = stock - 10 WHERE id = 5");
  await sleep(20);
  await q("A", "ROLLBACK");
}
async function requestB() {                       // an unrelated request: one auto-committed update
  await sleep(10);
  await q("B", "UPDATE products SET stock = stock - 1 WHERE id = 5");
  console.log("B: done, stock is now", await stock());
}

await Promise.all([requestA(), requestB()]);
console.log("final stock:", await stock(), "(expected 49: A rolled back, B's update kept)");
await pool.end();

What's the final stock?

Show answer

50. A's ROLLBACK also undid B's update.

Result
A: START TRANSACTION                                    on connection 2298
B: UPDATE products SET stock = stock - 1 WHERE id = 5   on connection 2298
B: done, stock is now 49
A: UPDATE products SET stock = stock - 10 WHERE id = 5  on connection 2298
A: ROLLBACK                                             on connection 2298
final stock: 50 (expected 49: A rolled back, B's update kept)
What’s happening
  1. A's pool.query("START TRANSACTION") borrows connection 2298, opens a transaction on that connection, and returns the connection to the pool — with the transaction still open.
  2. 10 ms later B borrows a free connection. mysql2 hands out the most recently released one: 2298. B's "auto-committed" update runs inside A's open transaction, and B's own check reads 49 on the same connection, so B believes its write is done and returns success.
  3. A's update also lands on 2298, inside the same transaction, and then A's ROLLBACK rolls back everything on that connection since START TRANSACTION: A's change and B's. The stock is back to 50; B's committed-looking write is lost, and nothing logged an error.
  4. Under other timings the statements would land on different connections instead: A's update would auto-commit on its own and the rollback would undo nothing. Either way there is no transaction. On a quiet developer machine the bug can stay hidden, because sequential calls happen to reuse one connection.
  5. The fix is the pattern above: const conn = await pool.getConnection(), every statement on conn, release() in finally. Libraries' transaction helpers (knex.transaction, sequelize.transaction, prisma.$transaction, db.transaction) do exactly that for you.
Open in topic →

How do you run a transaction with a connection pool in Node?

Show answer

I check out one connection with pool.getConnection(), call beginTransaction(), run every statement on that connection, commit() at the end, rollback() in the catch and rethrow, and release() in finally so the connection always goes back. The bug to avoid is sending START TRANSACTION and the statements through pool.query(): each call can land on a different connection, so there's no atomicity, and an open transaction can be left on a pooled connection where other requests' writes get swept into it and rolled back. For deadlocks I wrap the whole transaction in a retry with backoff on ER_LOCK_DEADLOCK, which means the function must be safe to repeat, and I keep slow external calls out of the transaction.

Open in topic →

How do you export millions of rows from MySQL in Node without running out of memory?

Show answer

I don't load them with one await query(), because mysql2 buffers the whole result into an array — in a test, half a million rows took the process from 61 MB to over 300 MB. Instead I stream: the callback connection's query().stream() gives a Readable of rows, and pipeline() into a transform and the response or file propagates backpressure, so memory stays flat and MySQL pauses when the consumer is slow. Because a stream holds its connection and an open snapshot for as long as the consumer takes, I use a dedicated connection for exports, or page through with keyset pagination so each query is short and the job can resume.

Open in topic →

What does a query builder like Knex give you over raw SQL?

Show answer

Safe composition: I build queries with method calls, so optional filters, sorting and pagination are added conditionally without concatenating strings, and every value is a bound parameter. It also gives dialect differences handled for me, a pool, transactions bound to one connection with knex.transaction, and migrations. I still think in SQL — joins, group by, raw expressions — which is why I like it for reporting and data-heavy code. The caveats are the raw escape hatches, which need bindings like anything else, MySQL-specific gaps like no RETURNING, and loose TypeScript types.

Open in topic →

What are the pros and cons of using an ORM like Sequelize?

Show answer

Pros: models and associations give a consistent object API, relations load with include, validation and hooks live next to the model, values are parameterised, and transactions are managed. Cons: the SQL is hidden, so it's easy to write N+1 queries with lazy getters or a join that multiplies rows; complex reports are awkward and end up as raw SQL anyway; and you must pass the transaction to every call or statements silently escape it. I use an ORM for CRUD-heavy domain code, turn on query logging in development, check the generated SQL for hot paths, and drop to SQL or a builder for reports and bulk work.

Open in topic →
InterviewCh 13 Prisma

How is Prisma different from Sequelize?

Show answer

Prisma is schema-first: models live in schema.prisma, prisma generate produces a fully typed client, and Prisma Migrate turns schema changes into SQL migrations. Query results are typed from exactly what you select or include, so a renamed column becomes a compile error. Sequelize defines models in JavaScript at runtime, returns model instances with methods, and its types are weaker. Prisma loads relations with one batched query per level rather than a join by default, and batches same-tick findUnique calls, so classic N+1 is harder to write. Since Prisma 7 the engine is TypeScript plus a WebAssembly compiler and it connects through driver adapters — @prisma/adapter-mariadb for MySQL. For SQL it can't express there's $queryRaw, which is parameterised.

Open in topic →
InterviewCh 13 Drizzle

Why would you pick Drizzle over Prisma?

Show answer

Drizzle is a thin, typed layer over SQL: tables are TypeScript definitions, the builder maps one-to-one to SQL, the result types come from the query, and there's no generation step or engine — it runs on the driver you already have, which suits serverless and edge runtimes. Prisma gives a higher-level, generated client with a separate schema language, nested writes and a mature migration workflow, at the cost of more abstraction between you and the SQL. I'd pick Drizzle when the team thinks in SQL and wants control over every query with types, and Prisma when the team wants the most guided, schema-driven CRUD experience. Both protect against injection and both need the SQL log checked on hot paths.

Open in topic →

The half-applied migration

A third migration adds a column and an index, with a typo in the index:

JavaScript
// migrations/20261016092000_loyalty.mjs
export async function up(knex) {
  await knex.schema.alterTable("customers", (t) => {
    t.integer("loyalty_points").notNullable().defaultTo(0);
  });
  await knex.schema.alterTable("customers", (t) => {
    t.index(["loyalty_point"]);                  // typo: the column is loyalty_points
  });
}
export async function down(knex) {
  await knex.schema.alterTable("customers", (t) => t.dropColumn("loyalty_points"));
}

Knex runs each migration in a transaction by default. The index fails. What state is the table in, and what happens when you fix the typo and run latest again?

Show answer

The column stays, the migration is still "pending", and the rerun fails on the column.

Result
$ node migrate.mjs latest
migration file "20261016092000_loyalty.mjs" failed
migration failed with error: alter table `customers` add index `customers_loyalty_point_index`(`loyalty_point`) - Key column 'loyalty_point' doesn't exist in table
migration failed: ER_KEY_COLUMN_DOES_NOT_EXITS Key column 'loyalty_point' doesn't exist in table
$ node migrate.mjs status
applied: [
  '20261016090000_create_customers.mjs',
  '20261016091000_add_phone_and_city.mjs'
] pending: [ '20261016092000_loyalty.mjs' ]
customers columns: id, name, email, created_at, phone, city, loyalty_points
$ node migrate.mjs latest        # after fixing the typo
migration file "20261016092000_loyalty.mjs" failed
migration failed with error: alter table `customers` add `loyalty_points` int not null default '0' - Duplicate column name 'loyalty_points'
migration failed: ER_DUP_FIELDNAME Duplicate column name 'loyalty_points'
What’s happening
  1. The first ALTER TABLE adds loyalty_points. In MySQL, DDL statements cause an implicit commit (see Autocommit and implicit commits): the column is committed the moment it's created, whatever transaction Knex opened.
  2. The second ALTER TABLE fails (ER_KEY_COLUMN_DOES_NOT_EXITS — MySQL's own spelling). Knex rolls back its transaction, which undoes nothing that matters, and doesn't record the migration in knex_migrations.
  3. So the database is half-migrated: status says the migration is pending, but the table already has loyalty_points.
  4. After fixing the typo, latest runs the migration from the top, and the first statement now fails with Duplicate column name 'loyalty_points'. The only ways out are a manual ALTER TABLE … DROP COLUMN or editing the migration to skip what exists.
  5. PostgreSQL has transactional DDL, so there the whole migration would roll back cleanly. On MySQL, write one DDL statement per migration, or make each step idempotent (if (!(await knex.schema.hasColumn("customers", "loyalty_points")))), and test migrations against a copy of production before running them there.
Open in topic →

How do you handle database migrations in a Node project?

Show answer

Schema changes are versioned migration files in the repo, applied in order by a tool that records what's run in a table — Knex or Sequelize migrations if we write them by hand, Prisma Migrate or drizzle-kit if they're generated from the schema, in which case every generated file is reviewed, because a diff tool will happily drop a table it doesn't know about. On MySQL, DDL commits implicitly, so a migration that fails halfway leaves the schema half-changed; I keep one DDL statement per migration or make steps idempotent. Migrations run as a separate deploy step with their own privileged account, changes are backward compatible so old and new code can run during the rollout — expand, migrate, contract — and I roll forward with new migrations rather than relying on down.

Open in topic →

What is the N+1 query problem and how do you fix it?

Show answer

It's fetching a list with one query and then running one more query per item to get related data — 1 query for the customers and N for their orders. Each query is quick, but the round trips add up with latency × N, so it's invisible locally and slow in production; in a test with 1,000 customers, lazy loading sent 1,001 queries where an include sent one join and batched loading sent two. The fixes: eager-load with a join or include, batch with one WHERE id IN (…) query and group in code — what DataLoader does for GraphQL — or, if I only need counts or sums, aggregate in SQL. I catch it by logging queries in development, asserting query counts per request in tests, and looking for high-count statements in performance_schema or APM traces.

Open in topic →

Why are database connections a problem with serverless functions, and how do you solve it?

Show answer

Every concurrent invocation can be a separate instance with its own pool, so connections scale with concurrency instead of with a fixed number of servers, and frozen instances keep idle connections open — they can't even run their idle timers. A spike quickly hits max_connections and requests fail with "Too many connections" while the database is idle; in a simulation, 30 instances against a limit of 20 gave 11 failures. Small pools with one connection and idle timeouts reduce waste but don't fix bursts. The fix is a connection proxy that multiplexes many clients onto a few server connections — RDS Proxy, ProxySQL, or the provider's pooler — or capping function concurrency below the connection budget, or a database with an HTTP or serverless driver. I'd also keep transactions short, since a proxy has to pin a connection for the duration of a transaction.

Open in topic →

What's the fundamental difference between MySQL and PostgreSQL?

Show answer

"They solve the same problem with different priorities. MySQL was built for speed and simplicity in web workloads: a server with pluggable storage engines, InnoDB in practice, a thread per connection, easy replication, and historically lenient type handling — though strict mode is the default now. PostgreSQL prioritises correctness and extensibility: strict types, transactional DDL, a process per connection, a rich type system — arrays, JSONB, ranges — more index types, and extensions like PostGIS or pgvector. In practice: same SQL basics, but PostgreSQL refuses to guess where MySQL sometimes still converts silently, and it's case-sensitive on strings by default."

Open in topic →

What's the difference between json and jsonb in PostgreSQL, and how does MySQL compare?

Show answer

"json stores the exact input text — whitespace, key order, duplicate keys — and re-parses it on every access. jsonb stores a decomposed binary form: keys sorted and de-duplicated, faster to query, and indexable with a GIN index that covers the whole document, so containment queries with @> on any key can use one index. You almost always want jsonb. MySQL has a single JSON type that behaves like jsonb — binary and normalised — but it can't index a whole document; you index specific paths with functional or multi-valued indexes."

Open in topic →

Predict the result on each engine

A login form looks up the user by the email they typed, with the sample data loaded in both databases:

SQL
SELECT COUNT(*) AS matches FROM customers WHERE email = 'ROHIT@example.com';
Show answer

MySQL finds Rohit, PostgreSQL finds nobody:

Result
-- MySQL:
+---------+
| matches |
+---------+
|       1 |
+---------+
-- PostgreSQL:
 matches 
---------
       0
(1 row)
What’s happening
  1. The stored email is rohit@example.com, all lower case.
  2. MySQL compares with the column's collation, utf8mb4_0900_ai_ci — case-insensitive — so ROHIT@… equals rohit@…: 1 match.
  3. PostgreSQL's default collation is deterministic and case-sensitive: different bytes, no match. After a port, users who type their email with a capital letter suddenly "don't exist".
  4. Fix in PostgreSQL: normalise on write (lower(email) stored, with a CHECK (email = lower(email))), or compare lower(email) = lower($1) backed by a unique index on lower(email), or use the citext type.
Open in topic →

A failed statement inside a transaction

The same script runs on both. How many rows survive?

SQL
CREATE TABLE quiz_t (id INT PRIMARY KEY);
BEGIN;
INSERT INTO quiz_t VALUES (1);
INSERT INTO quiz_t VALUES (1);
INSERT INTO quiz_t VALUES (2);
COMMIT;
SELECT COUNT(*) AS rows_kept FROM quiz_t;
Show answer

MySQL keeps 2 rows; PostgreSQL keeps 0.

Result
-- MySQL:
ERROR 1062 (23000): Duplicate entry '1' for key 'quiz_t.PRIMARY'
+-----------+
| rows_kept |
+-----------+
|         2 |
+-----------+
-- PostgreSQL:
CREATE TABLE
BEGIN
INSERT 0 1
ERROR:  duplicate key value violates unique constraint "quiz_t_pkey"
DETAIL:  Key (id)=(1) already exists.
ERROR:  current transaction is aborted, commands ignored until end of transaction block
ROLLBACK
 rows_kept 
-----------
         0
(1 row)
What’s happening
  1. In MySQL a failed statement rolls back only that statement. The transaction stays open, INSERT … (2) succeeds, and COMMIT commits rows 1 and 2. It's up to the application to notice the error and decide whether to roll back.
  2. In PostgreSQL an error puts the whole transaction into an aborted state: every following statement fails with "current transaction is aborted", and COMMIT actually performs a ROLLBACK (psql prints ROLLBACK). Row 1 is gone too.
  3. To keep going after an expected error in PostgreSQL, wrap the risky statement in a SAVEPOINT and ROLLBACK TO SAVEPOINT on failure (or use ON CONFLICT DO NOTHING here).
  4. Code ported from MySQL that "ignores duplicate errors and carries on" silently loses whole transactions on PostgreSQL — another difference that produces no error you'd notice in a log.
Open in topic →

What changes when you port a MySQL application to PostgreSQL?

Show answer

"Mechanical things first: backticks become double quotes or disappear, AUTO_INCREMENT becomes an identity column, UPDATE … JOIN becomes UPDATE … FROM, ON DUPLICATE KEY UPDATE becomes ON CONFLICT, and LAST_INSERT_ID becomes RETURNING. Then the semantic ones, which don't error: string comparison is case-sensitive in PostgreSQL, integer division truncates, implicit casts that MySQL allowed fail, and unquoted identifiers fold to lower case. Unsigned types and inline ENUMs need replacing. On the plus side, DDL becomes transactional, so migrations roll back cleanly. I'd run the test suite against PostgreSQL early, because the silent differences only show up in results."

Open in topic →

How do upserts differ between MySQL and PostgreSQL?

Show answer

"Both are atomic and keyed on a unique index. MySQL's INSERT … ON DUPLICATE KEY UPDATE reacts to a conflict on any unique key, refers to the new values with a row alias — or the older VALUES() function — and reports 1 for an insert, 2 for an update and 0 if nothing changed; there's no RETURNING, so to get the id I use the LAST_INSERT_ID(id) trick. PostgreSQL's ON CONFLICT names the conflict target, uses the EXCLUDED pseudo-row, can add a WHERE to skip no-op updates, and RETURNING gives back the rows — in PostgreSQL 18 with old and new values. PostgreSQL also has MERGE for batch syncs. In both, an upsert that updates can still consume an auto-increment value."

Open in topic →

How does MVCC differ between InnoDB and PostgreSQL?

Show answer

"Both keep old row versions so readers get a snapshot without blocking writers. InnoDB updates rows in place and writes the previous values to undo logs; readers that need an older version rebuild it from undo, and a purge thread discards undo nobody needs. PostgreSQL writes a whole new tuple on every update and leaves the old one in the table, marked with xmin and xmax; VACUUM later reclaims dead tuples, and autovacuum does that automatically. So PostgreSQL tables bloat if vacuum can't keep up, and it also has to freeze tuples to avoid transaction ID wraparound, while InnoDB keeps tables compact but has slow rollbacks of big transactions. In both, a long-running transaction is the enemy: it blocks vacuum in PostgreSQL and purge in InnoDB."

Open in topic →

Why do people say PostgreSQL is more extensible?

Show answer

"Because extensions can add first-class types, operators, functions and even index access methods that run inside the database, with full transactional and planner support. PostGIS adds geography with GiST indexes, pgvector adds vector types with HNSW indexes, pg_trgm makes LIKE '%x%' indexable with GIN, TimescaleDB adds time-series partitioning. Built in, PostgreSQL already has GIN, GiST, BRIN, partial and covering indexes. MySQL's InnoDB has B-tree, full-text, spatial and multi-valued indexes, and plugins can't add new index types — so specialised workloads usually mean a second system next to MySQL."

Open in topic →

MySQL or PostgreSQL for a new project — how would you decide?

Show answer

"For a standard web app either works, so I'd start with the team's experience and the hosting options. Then the deciding factors: if the data needs rich types — jsonb with GIN indexes, arrays, ranges, geospatial, vectors — or complex analytical SQL, PostgreSQL, because those are built in or one extension away. If it's very high-volume, simple OLTP and the team knows MySQL, or we expect to shard with Vitess, MySQL is a strong choice. I'd also weigh operations: PostgreSQL needs a connection pooler and attention to autovacuum; MySQL needs care with collations and with schema changes on big tables. With no strong constraints, I'd default to PostgreSQL today for its type system and extensions."

Open in topic →

"How would you find the Nth highest salary?"

Show answer

"First I'd ask whether ties count once — usually they do, so I want the Nth distinct salary. On MySQL 8 or later I'd use DENSE_RANK() OVER (ORDER BY salary DESC) and filter on the rank, because it handles ties and extends to 'per department' with a PARTITION BY. For a single value, SELECT DISTINCT salary … ORDER BY salary DESC LIMIT 1 OFFSET n-1 also works, and I'd wrap it in a scalar subquery so I get NULL rather than no row when there isn't an Nth salary. On old versions without window functions, a correlated subquery that counts how many distinct salaries are higher does the same job, but it's quadratic."

Open in topic →

Second highest salary — and what if there isn't one?

Write a query that returns the second highest salary from employees as a single column called second_highest. If there is no second highest salary (for example in a department with fewer than two distinct salaries), it should return NULL, not an empty result.

employees (salary column, highest first)
185000.00  142000.00  142000.00  130000.00  118000.00
 99000.00   95000.00   91000.00   88000.00   72000.00
Show answer

The answer is 142,000. The simplest query that's correct for ties and returns NULL when there's no answer is "the highest salary that's lower than the highest salary":

SQL
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Result
+----------------+
| second_highest |
+----------------+
|      142000.00 |
+----------------+
What’s happening
  1. The subquery (SELECT MAX(salary) FROM employees) runs once and returns 185000.00 — it's not correlated, so MySQL evaluates it a single time.
  2. The WHERE keeps every row with salary < 185000: nine rows, from Ben's 142000 down to Isla's 72000. Asha is the only row removed.
  3. MAX(salary) over those nine rows is 142000.00. Ben and Chloe both have it, but MAX returns a value, not a row, so the tie can't produce two results.
  4. The NULL requirement comes for free: an aggregate without GROUP BY always returns exactly one row. If the WHERE matched nothing, MAX over an empty set is NULL.
  5. The limitation is that it only generalises to "third highest" by nesting another level, which gets ugly fast — that's where the next two forms win.

Alternative 1: DISTINCT + LIMIT/OFFSET, wrapped so it returns NULL. Skip one distinct salary and take the next. On its own this returns no row when there's no second salary, so the problem's trick is to wrap it in a scalar subquery. Here it's run for Research (department 4), which has no employees, to show the difference:

SQL
SELECT DISTINCT salary FROM employees
WHERE department_id = 4
ORDER BY salary DESC LIMIT 1 OFFSET 1;

SELECT (SELECT DISTINCT salary FROM employees
        WHERE department_id = 4
        ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second_highest;
Result
Empty set

+----------------+
| second_highest |
+----------------+
|           NULL |
+----------------+
What’s happening
  1. SELECT DISTINCT salary … ORDER BY salary DESC produces the distinct salaries highest first. For the whole table that's 185000, 142000, 130000, … — the duplicate 142000 collapses to one.
  2. LIMIT 1 OFFSET 1 skips one row and returns the next, so for the whole table it returns 142000.00.
  3. For Research there are no rows at all, so the bare query returns an empty set — zero rows, which an application or a test harness sees as "no answer", not as NULL.
  4. Wrapping it as a scalar subquery in an outer SELECT with no FROM changes that: the outer query always produces one row, and a scalar subquery that finds no row evaluates to NULL.
  5. Without DISTINCT this form breaks on ties — see the next question.

Alternative 2: DENSE_RANK (MySQL 8.0+). Number the distinct salaries and pick rank 2:

SQL
WITH ranked AS (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT DISTINCT salary AS second_highest FROM ranked WHERE rnk = 2;
Result
+----------------+
| second_highest |
+----------------+
|      142000.00 |
+----------------+
What’s happening
  1. The window function gives every row a rank: Asha 1, Ben 2, Chloe 2, Elena 3… Ties share a rank and DENSE_RANK never skips a number.
  2. WHERE rnk = 2 keeps Ben's and Chloe's rows — two rows with the same salary.
  3. DISTINCT collapses them to one value. Without it you'd return 142000.00 twice.
  4. The filter has to sit in an outer query (a CTE or derived table): window functions are computed after WHERE, so WHERE DENSE_RANK() OVER (…) = 2 isn't allowed in the same SELECT.
  5. Like the LIMIT form, this returns an empty set when there's no rank 2, so wrap it the same way if NULL is required.
ApproachTiesGeneralises to N"No answer"Needs
MAX(…) WHERE salary < MAXCorrectOnly by nestingNULL automaticallyAny version
DISTINCT … LIMIT 1 OFFSET n-1Correct only with DISTINCTYes (literal offset)Empty set unless wrappedAny version
DENSE_RANK()CorrectYes, and per group with PARTITION BYEmpty set unless wrappedMySQL 8.0+

Learn more: ROW_NUMBER, RANK and DENSE_RANK and Subqueries.

Open in topic →

Spot the bug: the "third highest salary" that returns 142,000

A colleague wrote this to find the third highest salary. What does it return, and what's wrong with it?

SQL
SELECT salary FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
Show answer

It returns 142,000, which is the second highest salary. The third highest distinct salary is 130,000. The bug is the missing DISTINCT: OFFSET counts rows, and the tie between Ben and Chloe uses up two of them.

SQL
SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 2;
Result
+-----------+
| salary    |
+-----------+
| 142000.00 |
+-----------+

+-----------+
| salary    |
+-----------+
| 130000.00 |
+-----------+
What’s happening
  1. Sorted highest first, the rows are 185000, 142000, 142000, 130000, …. OFFSET 2 skips the first two rows — Asha's and one of the two 142,000 rows.
  2. The next row is the other 142,000, so the buggy query returns 142000.00.
  3. With DISTINCT, the sorted list becomes 185000, 142000, 130000, … — duplicates are removed before ORDER BY and LIMIT are applied (logical order: SELECT DISTINCT, then ORDER BY, then LIMIT).
  4. Skipping two values now lands on 130000.00, the correct third highest.
  5. The bug is invisible on test data without ties, which is exactly why interviewers put a tie in the data. Asking "do ties count once?" before you write the query shows you've seen it.

Learn more: LIMIT and OFFSET and DISTINCT.

Open in topic →

Nth highest salary as a function — why does LIMIT N-1 fail?

Write a stored function nth_highest_salary(n INT) that returns the Nth highest distinct salary, or NULL if there isn't one. This first attempt doesn't even compile — what's the error, and how do you fix it?

SQL
CREATE FUNCTION nth_highest_salary(n INT) RETURNS DECIMAL(10,2)
READS SQL DATA
RETURN (SELECT DISTINCT salary FROM employees
        ORDER BY salary DESC LIMIT n - 1, 1);
Show answer

MySQL's LIMIT only accepts integer literals, ? placeholders, or stored-program variables and parameters — not expressions. n - 1 is an expression, so it's a syntax error:

Result
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '- 1, 1)' at line 3

The fix is to compute the offset into a local variable first, then use the variable in LIMIT:

SQL
DELIMITER //
CREATE FUNCTION nth_highest_salary(n INT) RETURNS DECIMAL(10,2)
READS SQL DATA
BEGIN
  DECLARE skip INT DEFAULT n - 1;
  RETURN (SELECT DISTINCT salary FROM employees
          ORDER BY salary DESC LIMIT skip, 1);
END//
DELIMITER ;

SELECT nth_highest_salary(1) AS n1, nth_highest_salary(2) AS n2,
       nth_highest_salary(3) AS n3, nth_highest_salary(9) AS n9;
Result
+-----------+-----------+-----------+----------+
| n1        | n2        | n3        | n9       |
+-----------+-----------+-----------+----------+
| 185000.00 | 142000.00 | 130000.00 | 72000.00 |
+-----------+-----------+-----------+----------+
What’s happening
  1. DELIMITER // tells the mysql client not to end the statement at the first ; inside the function body. It's a client feature, not SQL; GUI tools and drivers don't need it.
  2. DECLARE skip INT DEFAULT n - 1 evaluates the expression once and stores it. LIMIT skip, 1 is legal because skip is a local variable, which MySQL allows in LIMIT inside stored programs (since 5.5).
  3. LIMIT skip, 1 is the two-argument form: offset first, then row count. For n = 3, it skips two distinct salaries (185000, 142000) and returns 130000.00.
  4. There are only nine distinct salaries (ten employees, one tie), so n9 is the lowest, 72000.00, and nth_highest_salary(10) would find no row — the RETURN (subquery) then returns NULL, which is what the spec asks for.
  5. READS SQL DATA declares that the function reads but doesn't modify data. Leave it out and, with binary logging on (the default since 8.0), CREATE FUNCTION fails with ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled.

Alternative 1: a prepared statement. Outside a stored program, LIMIT ? takes a placeholder, so application code (or a session) can bind the offset:

SQL
SET @skip = 2;
PREPARE stmt FROM 'SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT ?, 1';
EXECUTE stmt USING @skip;
DEALLOCATE PREPARE stmt;
Result
+-----------+
| salary    |
+-----------+
| 130000.00 |
+-----------+
What’s happening
  1. PREPARE parses the statement once with ? standing in for the offset. It's the same mechanism drivers like mysql2 use for execute().
  2. EXECUTE … USING @skip binds 2, so the query skips two distinct salaries and returns 130000.00.
  3. This is how you'd do it from Node: compute n - 1 in JavaScript and pass it as a parameter — never by concatenating it into the SQL string.

Alternative 2: no LIMIT, no window functions. The pre-8.0 classic: a salary is the Nth highest if exactly N - 1 distinct salaries are higher than it.

SQL
SELECT DISTINCT e1.salary
FROM employees e1
WHERE 3 - 1 = (SELECT COUNT(DISTINCT e2.salary)
               FROM employees e2
               WHERE e2.salary > e1.salary);
Result
+-----------+
| salary    |
+-----------+
| 130000.00 |
+-----------+
What’s happening
  1. For each row e1, the correlated subquery counts the distinct salaries strictly greater than e1.salary.
  2. For Elena (130000) the higher distinct salaries are 185000 and 142000, so the count is 2, which equals 3 - 1. She's kept.
  3. For Ben and Chloe (142000) the count is 1; for Dev (118000) it's 3. Neither matches.
  4. DISTINCT in the outer query matters when several people share the Nth salary — try it with 2 - 1 and you'd get Ben and Chloe's 142000 twice without it.
  5. The cost: the subquery runs once per row, so it's O(n²) without an index on salary. It's the answer to "how would you do it without window functions?", not the one to ship.

The window-function version for any N is SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees) AS r WHERE rnk = 3, which also returned 130000.00.

Learn more: Stored functions and SQL injection and prepared statements.

Open in topic →

Rank the salaries three ways — predict ROW_NUMBER, RANK and DENSE_RANK

Predict the three ranking columns for the top six salaries.

SQL
SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
       RANK()       OVER (ORDER BY salary DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense
FROM employees
ORDER BY salary DESC, name
LIMIT 6;
Show answer

Ben and Chloe tie on 142,000. ROW_NUMBER gives them 2 and 3, RANK gives both 2 and then jumps to 4, DENSE_RANK gives both 2 and continues with 3.

Result
+-------+-----------+---------+-----+-------+
| name  | salary    | row_num | rnk | dense |
+-------+-----------+---------+-----+-------+
| Asha  | 185000.00 |       1 |   1 |     1 |
| Ben   | 142000.00 |       2 |   2 |     2 |
| Chloe | 142000.00 |       3 |   2 |     2 |
| Elena | 130000.00 |       4 |   4 |     3 |
| Dev   | 118000.00 |       5 |   5 |     4 |
| Grace |  99000.00 |       6 |   6 |     5 |
+-------+-----------+---------+-----+-------+
What’s happening
  1. All three functions sort by salary DESC inside the window. Asha is first everywhere: 1, 1, 1.
  2. ROW_NUMBER numbers rows 1, 2, 3, … with no sharing. Ben and Chloe tie, so which of them gets 2 is not defined by the query — here Ben got 2, but nothing guarantees it. Add a tiebreaker (ORDER BY salary DESC, id) when you need a stable result.
  3. RANK is "1 + the number of rows strictly ahead of me". Ben and Chloe have one row ahead (Asha), so both are 2. Elena has three rows ahead, so she's 4 — the gap is the "missing" 3.
  4. DENSE_RANK is "1 + the number of distinct values ahead of me". Elena has two distinct salaries ahead, so she's 3. No gaps, ever.
  5. The outer ORDER BY salary DESC, name only controls display order; it doesn't change how the window functions numbered the rows.

Before MySQL 8.0 there were no window functions, and you'd compute ranks with correlated subqueries. Both give the same numbers as above:

SQL
SELECT e1.name, e1.salary,
       (SELECT COUNT(DISTINCT e2.salary) FROM employees e2
        WHERE e2.salary >= e1.salary) AS dense,
       (SELECT COUNT(*) FROM employees e2
        WHERE e2.salary > e1.salary) + 1 AS rnk
FROM employees e1
ORDER BY e1.salary DESC, e1.name
LIMIT 6;
Result
+-------+-----------+-------+------+
| name  | salary    | dense | rnk  |
+-------+-----------+-------+------+
| Asha  | 185000.00 |     1 |    1 |
| Ben   | 142000.00 |     2 |    2 |
| Chloe | 142000.00 |     2 |    2 |
| Elena | 130000.00 |     3 |    4 |
| Dev   | 118000.00 |     4 |    5 |
| Grace |  99000.00 |     5 |    6 |
+-------+-----------+-------+------+
What’s happening
  1. dense counts distinct salaries greater than or equal to mine. For Elena: 185000, 142000, 130000 → 3.
  2. rnk counts rows strictly greater than mine and adds one. For Elena: Asha, Ben, Chloe → 3 + 1 = 4.
  3. The definitions are exactly the ones in the walkthrough above, written out by hand — which is a good way to show you understand what the window functions compute.
  4. Each subquery runs once per outer row, so this is quadratic; with window functions MySQL sorts once and assigns ranks in a single pass.

NTILE(4) OVER (ORDER BY salary DESC) is the related "bucket" function: on this data it put Asha, Ben and Chloe in quartile 1 and Hiro and Isla in quartile 4, because ten rows don't split evenly and the earlier buckets get the extra rows.

Learn more: ROW_NUMBER, RANK and DENSE_RANK and Correlated subqueries.

Open in topic →

Median salary — overall and per department

MySQL has no MEDIAN() function. Find the median salary of all employees, then the median per department.

Show answer

The overall median is 108,500: with ten salaries, it's the average of the 5th and 6th (99,000 and 118,000). The trick is to number the rows, count them, and average the one or two middle rows:

SQL
WITH ordered AS (
  SELECT salary,
         ROW_NUMBER() OVER (ORDER BY salary) AS rn,
         COUNT(*)     OVER ()                AS cnt
  FROM employees
)
SELECT AVG(salary) AS median
FROM ordered
WHERE rn IN (FLOOR((cnt + 1) / 2), CEIL((cnt + 1) / 2));
Result
+---------------+
| median        |
+---------------+
| 108500.000000 |
+---------------+
What’s happening
  1. ROW_NUMBER() OVER (ORDER BY salary) numbers the salaries lowest first: Isla 1 (72,000) … Asha 10 (185,000).
  2. COUNT(*) OVER () — an empty window — puts the total row count, 10, on every row, so the outer query can use it without a second query.
  3. With cnt = 10, (cnt + 1) / 2 is 5.5. FLOOR gives 5 and CEIL gives 6, so rows 5 and 6 are kept: Grace (99,000) and Dev (118,000).
  4. AVG of those two is 108500. For an odd count, say 9, (9 + 1) / 2 is exactly 5, FLOOR and CEIL agree, and AVG of one row is just that row — so one formula covers both cases.
  5. Compare the mean: AVG(salary) over everyone is 116200. Asha's 185,000 pulls the mean up but barely moves the median, which is why medians are used for salaries.

Per department is the same query with PARTITION BY on both window functions:

SQL
WITH ordered AS (
  SELECT department_id, salary,
         ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary) AS rn,
         COUNT(*)     OVER (PARTITION BY department_id)                 AS cnt
  FROM employees
  WHERE department_id IS NOT NULL
)
SELECT department_id, AVG(salary) AS median, MIN(cnt) AS employees
FROM ordered
WHERE rn IN (FLOOR((cnt + 1) / 2), CEIL((cnt + 1) / 2))
GROUP BY department_id;
Result
+---------------+---------------+-----------+
| department_id | median        | employees |
+---------------+---------------+-----------+
|             1 | 142000.000000 |         4 |
|             2 |  99000.000000 |         3 |
|             3 |  80000.000000 |         2 |
+---------------+---------------+-----------+
What’s happening
  1. PARTITION BY department_id restarts the numbering and the count for each department, so every row knows its position and its department's size.
  2. Engineering has 4 salaries (118k, 142k, 142k, 185k). Rows 2 and 3 are both 142,000, so the median is 142000.
  3. Sales has 3 (95k, 99k, 130k); (3 + 1) / 2 = 2, so only row 2 is kept: 99000.
  4. Support has 2 (72k, 88k); rows 1 and 2 are averaged: 80000.
  5. MIN(cnt) is just a way to show the group size: cnt is the same on every row of a group, and an aggregate is needed under ONLY_FULL_GROUP_BY. Jonas (no department) is filtered out; without the filter he'd form his own NULL group.

Learn more: Window functions: OVER and PARTITION BY.

Open in topic →

"How do you find and remove duplicate rows?"

Show answer

"Find them with GROUP BY on the columns that should be unique and HAVING COUNT(*) > 1. To see the full rows, I'd use COUNT(*) OVER (PARTITION BY email) or join back to that grouped list. To delete, I decide which copy survives — usually the lowest id or the newest row — and delete the others: a multi-table DELETE self-join, or ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) and delete where the row number is above 1. I'd run it in a transaction and check the count first. Then I add a UNIQUE index so it can't happen again, and handle collisions in the application with INSERT … ON DUPLICATE KEY UPDATE or by catching error 1062."

Open in topic →

Find the duplicate emails — and then the full duplicate rows

  1. List every email that appears more than once, with how many times.
  2. Then list the complete rows (id, name, date) of every duplicated email, so someone can decide which to keep.
Show answer

For part 1, group by the column that should be unique and keep groups with more than one row:

SQL
SELECT email, COUNT(*) AS copies
FROM signups
GROUP BY email
HAVING COUNT(*) > 1;
Result
+------------------+--------+
| email            | copies |
+------------------+--------+
| asha@example.com |      3 |
| ben@example.com  |      2 |
| cara@example.com |      2 |
+------------------+--------+
What’s happening
  1. GROUP BY email builds one group per email. Because the collation is case-insensitive, rows 4 and 7 go into the same group — more on that in the next question.
  2. COUNT(*) counts rows per group: asha 3, ben 2, cara 2, dan 1.
  3. HAVING filters groups, after aggregation. WHERE COUNT(*) > 1 would be an error, because WHERE runs before any grouping happens.
  4. The query can't show id or name: those differ inside a group, and under ONLY_FULL_GROUP_BY MySQL rejects non-aggregated columns that aren't grouped. That's why part 2 needs a different shape.

For part 2, the cleanest modern answer is a window count: every row learns how many rows share its email, without being collapsed.

SQL
SELECT id, email, name, signed_up, copies
FROM (
  SELECT s.*, COUNT(*) OVER (PARTITION BY email) AS copies
  FROM signups s
) AS t
WHERE copies > 1
ORDER BY email, id;
Result
+----+------------------+----------+------------+--------+
| id | email            | name     | signed_up  | copies |
+----+------------------+----------+------------+--------+
|  1 | asha@example.com | Asha     | 2025-01-03 |      3 |
|  3 | asha@example.com | Asha     | 2025-01-09 |      3 |
|  6 | asha@example.com | Asha     | 2025-02-01 |      3 |
|  2 | ben@example.com  | Ben      | 2025-01-04 |      2 |
|  5 | ben@example.com  | Benjamin | 2025-01-12 |      2 |
|  4 | cara@example.com | Cara     | 2025-01-10 |      2 |
|  7 | Cara@Example.com | Cara     | 2025-02-02 |      2 |
+----+------------------+----------+------------+--------+
What’s happening
  1. COUNT(*) OVER (PARTITION BY email) is the same count as part 1, but as a window function it's attached to every row instead of collapsing the group.
  2. The derived table t has all eight rows, each with its copies value: Dan's is 1.
  3. The outer WHERE copies > 1 removes Dan. It must be in an outer query because window functions are evaluated after WHERE.
  4. Sorting by email, id puts each set of duplicates together, oldest first — exactly the view you want before deciding which to delete.

Alternative: join back to the grouped list (works on MySQL 5.7 too):

SQL
SELECT s.*
FROM signups s
JOIN (SELECT email FROM signups
      GROUP BY email HAVING COUNT(*) > 1) d
  ON d.email = s.email
ORDER BY s.email, s.id;

The result is the same seven rows without the copies column.

What’s happening
  1. The derived table d is part 1's query reduced to the email column: asha, ben, cara.
  2. Joining signups to it keeps only rows whose email is in that list — a semi-join written as an inner join, safe here because d has one row per email, so nothing is multiplied.
  3. The trade-off: this scans signups twice (once to group, once to join), where the window version scans it once. On a big table with an index on email, both are fine; without one, the window version is usually cheaper.

A third form you'll see is a self-join, SELECT DISTINCT a.email FROM signups a JOIN signups b ON a.email = b.email AND a.id <> b.id. It returns the same three emails, but it compares every pair of rows within each group (Asha's three rows make six pairs), so it scales badly when one value has many copies.

Learn more: HAVING vs WHERE and Window functions: OVER and PARTITION BY.

Open in topic →

Predict: are Cara@Example.com and cara@example.com duplicates?

The column is VARCHAR(100) with the table's default character set, utf8mb4. Predict both results.

SQL
SELECT id, email FROM signups WHERE email = 'cara@example.com';

SELECT email COLLATE utf8mb4_bin AS email_exact, COUNT(*)
FROM signups
GROUP BY email_exact
HAVING COUNT(*) > 1;
Show answer

Yes, by default they're equal — searching for the lower-case spelling finds both rows — but with a binary collation they're different strings, and Cara drops out of the duplicates list.

Result
+----+------------------+
| id | email            |
+----+------------------+
|  4 | cara@example.com |
|  7 | Cara@Example.com |
+----+------------------+

+------------------+----------+
| email_exact      | COUNT(*) |
+------------------+----------+
| asha@example.com |        3 |
| ben@example.com  |        2 |
+------------------+----------+
What’s happening
  1. SELECT COLLATION(email) FROM signups returns utf8mb4_0900_ai_ci, MySQL 8.0+'s default. ai means accent-insensitive and ci case-insensitive, so C and c compare equal and the WHERE matches row 7 as well as row 4. (When a column is compared with a literal, the column's collation wins.)
  2. That's why the plain GROUP BY email in the previous question found three duplicate emails, and why a UNIQUE index on email would treat rows 4 and 7 as a collision.
  3. COLLATE utf8mb4_bin compares the raw code points instead. Now Cara@Example.com and cara@example.com are different groups of one row each, and only Asha and Ben remain.
  4. Which answer is right is a business question. For emails, case-insensitive is usually what you want (the domain part is case-insensitive, and users mistype case), so the default collation is helpful — but the safest design is to normalise on the way in (LOWER(TRIM(email))) so there's only one spelling stored.
  5. MySQL 5.7's default was latin1 / utf8mb4_general_ci depending on configuration; general_ci is also case-insensitive, so the same surprise applies on older servers.

Learn more: Strings: CHAR, VARCHAR, TEXT and character sets.

Open in topic →

Delete the duplicates, keeping the lowest id — why does the obvious query fail?

Delete every duplicate signup so that only the row with the lowest id per email survives. The obvious query is below. What happens when you run it, and what should you write instead?

SQL
DELETE FROM signups
WHERE id NOT IN (SELECT MIN(id) FROM signups GROUP BY email);
Show answer

MySQL refuses it. You can't read from the table you're deleting from in a subquery:

Result
ERROR 1093 (HY000): You can't specify target table 'signups' for update in FROM clause

The idiomatic MySQL fix is a multi-table DELETE with a self-join: delete every row for which a row with the same email and a smaller id exists.

SQL
START TRANSACTION;

DELETE s1
FROM signups s1
JOIN signups s2
  ON s1.email = s2.email
 AND s1.id > s2.id;

SELECT * FROM signups;
ROLLBACK;
Result
Query OK, 4 rows affected

+----+------------------+------+------------+
| id | email            | name | signed_up  |
+----+------------------+------+------------+
|  1 | asha@example.com | Asha | 2025-01-03 |
|  2 | ben@example.com  | Ben  | 2025-01-04 |
|  4 | cara@example.com | Cara | 2025-01-10 |
|  8 | dan@example.com  | Dan  | 2025-02-03 |
+----+------------------+------+------------+
What’s happening
  1. Error 1093 exists because MySQL would be reading signups while deleting from it, and the rows the subquery sees could change under it. PostgreSQL allows the original query (on PostgreSQL 18 the same DELETE … NOT IN (SELECT MIN(id) …) ran and deleted the duplicate); MySQL doesn't.
  2. In the self-join, s1 is the row that might be deleted and s2 is "another row with the same email". s1.id > s2.id matches when there's an older copy. Asha's id 3 matches id 1; id 6 matches ids 1 and 3.
  3. DELETE s1 (naming the alias) says which side of the join to delete from. Id 6 joined twice, but a row is only deleted once, so 4 rows affected is ids 3, 5, 6 and 7.
  4. Id 7 (Cara@Example.com) went too, because the case-insensitive collation says it equals id 4's email. Decide that before you run it.
  5. Wrapping it in START TRANSACTION … ROLLBACK let us inspect the result and undo it. In real life you'd check, then COMMIT.

Alternative 1: hide the subquery inside a derived table. Wrapping the subquery one level deeper makes MySQL materialise it into a temporary result first, so it no longer reads signups during the delete:

SQL
DELETE FROM signups
WHERE id NOT IN (
  SELECT keep_id FROM (
    SELECT MIN(id) AS keep_id FROM signups GROUP BY email
  ) AS keepers
);
Result
Query OK, 4 rows affected
What’s happening
  1. The inner query computes the ids to keep: 1, 2, 4, 8.
  2. Because it's a derived table (AS keepers), MySQL materialises it before the delete starts. The MySQL manual documents this as the exception to error 1093: it applies only "if … that derived table is materialized rather than merged into the outer query".
  3. NOT IN (1, 2, 4, 8) is safe here because MIN(id) from a NOT NULL primary key can't be NULL. With a nullable column, NOT IN plus a NULL deletes nothing — see Tricky NULL and JOIN puzzles.
  4. It leaves the same four rows as the self-join. It reads more clearly as "keep these", which some reviewers prefer.

Alternative 2: ROW_NUMBER (MySQL 8.0+). Number the rows inside each email and delete everything after the first. This is the most flexible form, because the ORDER BY decides which copy survives:

Starting dataThe four duplicates put back

Alternative 1 really deleted ids 3, 5, 6 and 7 (it ran without a transaction). Put them back exactly as practice.sql has them, so there are duplicates to delete again:

SQL
INSERT INTO signups VALUES
  (3, 'asha@example.com', 'Asha',     '2025-01-09'),
  (5, 'ben@example.com',  'Benjamin', '2025-01-12'),
  (6, 'asha@example.com', 'Asha',     '2025-02-01'),
  (7, 'Cara@Example.com', 'Cara',     '2025-02-02');
SQL
WITH ranked AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
  FROM signups
)
DELETE signups
FROM signups JOIN ranked USING (id)
WHERE ranked.rn > 1;
Result
Query OK, 4 rows affected
What’s happening
  1. The CTE numbers rows per email by id: Asha's 1, 3, 6 get rn 1, 2, 3; Ben's 2, 5 get 1, 2; and so on.
  2. The multi-table DELETE joins signups to the CTE on id and deletes rows with rn > 1: ids 3, 6, 5 and 7.
  3. MySQL allows a CTE before DELETE (8.0+), and the CTE is materialised, so there's no error 1093.
  4. To keep the newest copy instead, change only the window's order: ORDER BY signed_up DESC, id DESC. Run with that order, the survivors were ids 5, 6, 7 and 8 — Benjamin, Asha's February row, Cara@Example.com and Dan.
ApproachChooses the survivor byVersionNotes
DELETE s1 … JOIN s2 ON … s1.id > s2.idLowest id (flip to < for highest)AnyJoins every pair inside a group; fine for a few copies each
NOT IN (SELECT … FROM (derived))Whatever the inner aggregate picksAnyRelies on materialisation; careful with NULL
ROW_NUMBER() + DELETE … JOINAny ordering you like8.0+Most flexible; one pass to number rows

Learn more: UPDATE and DELETE with joins and Safe updates and the dangers of a missing WHERE.

Open in topic →

Stop duplicates coming back

You want a UNIQUE index on signups.email. What happens if you add it before cleaning up, and how should the application handle a sign-up for an email that already exists once the index is in place?

Show answer

The index can't be built while duplicates exist: MySQL checks every existing row and stops at the first collision.

Starting dataThe four duplicates put back again

Alternative 2 above deleted ids 3, 5, 6 and 7 again. Put them back, so the table has its duplicates as before the clean-up:

SQL
INSERT INTO signups VALUES
  (3, 'asha@example.com', 'Asha',     '2025-01-09'),
  (5, 'ben@example.com',  'Benjamin', '2025-01-12'),
  (6, 'asha@example.com', 'Asha',     '2025-02-01'),
  (7, 'Cara@Example.com', 'Cara',     '2025-02-02');
SQL
ALTER TABLE signups ADD UNIQUE KEY uq_email (email);
Result
ERROR 1062 (23000): Duplicate entry 'cara@example.com' for key 'signups.uq_email'

After the clean-up from the previous question, the same ALTER TABLE succeeds. Then a repeat sign-up is either an error, an upsert, or silently ignored — your choice:

Starting dataCleaned up, with the unique index

The clean-up from the previous question (the self-join DELETE, this time without ROLLBACK), then the same ALTER TABLE, which now succeeds:

SQL
DELETE s1
FROM signups s1
JOIN signups s2
  ON s1.email = s2.email
 AND s1.id > s2.id;

ALTER TABLE signups ADD UNIQUE KEY uq_email (email);
SQL
INSERT INTO signups VALUES (9, 'ASHA@example.com', 'Asha R', '2025-03-01');

INSERT INTO signups VALUES (9, 'ASHA@example.com', 'Asha R', '2025-03-01') AS new
  ON DUPLICATE KEY UPDATE name = new.name, signed_up = new.signed_up;

SELECT * FROM signups;
Result
ERROR 1062 (23000): Duplicate entry 'ASHA@example.com' for key 'signups.uq_email'

Query OK, 2 rows affected

+----+------------------+--------+------------+
| id | email            | name   | signed_up  |
+----+------------------+--------+------------+
|  1 | asha@example.com | Asha R | 2025-03-01 |
|  2 | ben@example.com  | Ben    | 2025-01-04 |
|  4 | cara@example.com | Cara   | 2025-01-10 |
|  8 | dan@example.com  | Dan    | 2025-02-03 |
+----+------------------+--------+------------+
What’s happening
  1. The failed ALTER TABLE names cara@example.com — the case-only duplicate — because the unique index uses the column's case-insensitive collation, exactly like GROUP BY did. Nothing is changed when it fails.
  2. With the index in place, a plain INSERT of ASHA@example.com fails with error 1062 too. That's the constraint doing its job: the database, not the application, is now the last line of defence against races.
  3. INSERT … AS new ON DUPLICATE KEY UPDATE turns the collision into an update of the existing row. new.name refers to the value you tried to insert. 2 rows affected is MySQL's convention for "an existing row was updated" (1 means inserted, 0 means nothing changed).
  4. Row 1 kept its id and its stored email spelling, but took the new name and date. Id 9 was never created.
  5. The row alias form (AS new) is MySQL 8.0.19+. Before that you'd write name = VALUES(name), which still works but has been deprecated since 8.0.20 and logs a warning.

INSERT IGNORE is the third option: it turns the error into a warning and inserts nothing. Run with ben@example.com, it returned Query OK, 0 rows affected, 1 warning, and SHOW WARNINGS showed 1062 | Duplicate entry 'ben@example.com' for key 'signups.uq_email'. Be careful: IGNORE also downgrades other errors (like bad values in strict mode) to warnings.

Learn more: Upserts: ON DUPLICATE KEY UPDATE and INSERT IGNORE and REPLACE.

Open in topic →

"How do you get the top row per group?"

Show answer

"On MySQL 8 and later I use a window function: ROW_NUMBER(), RANK() or DENSE_RANK() OVER (PARTITION BY group ORDER BY metric DESC) in a CTE, then filter on the rank in the outer query. The choice of function is the tie policy: ROW_NUMBER for exactly N rows, RANK or DENSE_RANK to keep ties. Before 8.0, I'd join the table to a GROUP BY of (group, MAX(metric)), or use a correlated subquery. The classic mistake is SELECT dept, name, MAX(salary) … GROUP BY dept — the name isn't guaranteed to belong to the max, and MySQL 5.7+ rejects it under ONLY_FULL_GROUP_BY."

Open in topic →

Highest-paid employee in each department, ties included

Return each department's name, the employee(s) with the highest salary in it, and the salary. If two people tie for the top, return both. Employees without a department are ignored.

employees joined to departments
Engineering: Asha 185000, Ben 142000, Chloe 142000, Dev 118000
Sales:       Elena 130000, Grace 99000, Farid 95000
Support:     Hiro 88000, Isla 72000
Research:    (nobody)          — and Jonas 91000 has no department
Show answer

The winners are Asha, Elena and Hiro. The most portable answer joins each employee to their department's maximum with a row-value IN:

SQL
SELECT d.name AS department, e.name AS employee, e.salary
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE (e.department_id, e.salary) IN (
  SELECT department_id, MAX(salary)
  FROM employees
  GROUP BY department_id
)
ORDER BY d.name;
Result
+-------------+----------+-----------+
| department  | employee | salary    |
+-------------+----------+-----------+
| Engineering | Asha     | 185000.00 |
| Sales       | Elena    | 130000.00 |
| Support     | Hiro     |  88000.00 |
+-------------+----------+-----------+
What’s happening
  1. The subquery is the GROUP BY that "knows the winning time": (1, 185000), (2, 130000), (3, 88000) and (NULL, 91000) for Jonas's missing department.
  2. (e.department_id, e.salary) IN (…) is a row constructor comparison: both values must match the same pair. Asha (1, 185000) matches; Ben (1, 142000) doesn't.
  3. Jonas's pair (NULL, 91000) never matches anything — NULL = NULL is unknown — and the inner join to departments would drop him anyway.
  4. Ties are kept automatically: if Ben earned 185,000 too, his pair would match and he'd appear alongside Asha.
  5. Research has no employees, so it has no maximum and doesn't appear. If the question wanted "every department, even empty ones", you'd start from departments with a LEFT JOIN.

Alternative 1: RANK() per department (MySQL 8.0+). The most readable version, and the one that generalises to "top 3":

SQL
WITH ranked AS (
  SELECT e.*, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
  FROM employees e
)
SELECT d.name AS department, r.name AS employee, r.salary
FROM ranked r JOIN departments d ON d.id = r.department_id
WHERE r.rnk = 1
ORDER BY d.name;

The result is the same three rows.

What’s happening
  1. PARTITION BY department_id restarts the ranking per department; ORDER BY salary DESC puts the highest first, so each department's top earner gets rnk = 1.
  2. RANK (not ROW_NUMBER) is what keeps ties: two people on the same top salary would both be 1.
  3. Filtering happens in the outer query because WHERE can't see window results in the same SELECT.
  4. One scan and one sort per partition, which usually beats the join-back form on large tables.

Alternative 2: "nobody in my department earns more" — an anti-join with LEFT JOIN … IS NULL:

SQL
SELECT d.name AS department, e.name AS employee, e.salary
FROM employees e
JOIN departments d ON d.id = e.department_id
LEFT JOIN employees richer
  ON richer.department_id = e.department_id
 AND richer.salary > e.salary
WHERE richer.id IS NULL
ORDER BY d.name;

The result is again Asha, Elena and Hiro.

What’s happening
  1. For each employee e, the LEFT JOIN looks for colleagues in the same department who earn more. Ben finds Asha; Dev finds Asha, Ben and Chloe.
  2. Asha finds nobody, so her row survives the outer join with richer.* all NULL.
  3. WHERE richer.id IS NULL keeps exactly those "no one richer" rows. Ties survive, because a colleague on the same salary isn't >.
  4. It works on any version and with any database, but it compares pairs within each group, so it gets slow when groups are large. With an index on (department_id, salary) it's fine for moderate sizes.

A fourth form is the correlated subquery WHERE e.salary = (SELECT MAX(e2.salary) FROM employees e2 WHERE e2.department_id = e.department_id), which also returned the same three rows and also keeps ties.

Learn more: Top N per group and Anti-joins and semi-joins.

Open in topic →

Spot the bug: the lowest-paid employee per department

This query is meant to show the lowest-paid employee in each department. What does MySQL 9.7 do with it, and what would it have returned on a server without ONLY_FULL_GROUP_BY?

SQL
SELECT department_id, name, MIN(salary) AS lowest
FROM employees
WHERE department_id IS NOT NULL
GROUP BY department_id;
Show answer

MySQL 9.7 rejects it, because name isn't grouped and isn't determined by department_id:

Result
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'ch15.employees.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

With the mode switched off (as on MySQL 5.6 and earlier, or a 5.7+ server configured loosely), it runs and returns wrong names:

SQL
SET SESSION sql_mode = REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '');
SELECT department_id, name, MIN(salary) AS lowest
FROM employees WHERE department_id IS NOT NULL
GROUP BY department_id;
Result
+---------------+-------+-----------+
| department_id | name  | lowest    |
+---------------+-------+-----------+
|             1 | Asha  | 118000.00 |
|             2 | Elena |  95000.00 |
|             3 | Hiro  |  72000.00 |
+---------------+-------+-----------+
What’s happening
  1. MIN(salary) is computed correctly per group: 118,000, 95,000 and 72,000.
  2. name isn't aggregated, so with the check off MySQL picks a value from any row of the group — in practice usually the first row it reads, which here is the lowest id. Asha, Elena and Hiro are the highest earners, so every name is wrong.
  3. Nothing ties the non-aggregated name to the row that produced MIN(salary). That's the fundamental point: aggregates are computed per column, independently.
  4. ONLY_FULL_GROUP_BY has been on by default since MySQL 5.7.5 precisely to stop this. ANY_VALUE(name) silences the error but doesn't fix anything — it just says "I accept an arbitrary name".
  5. The fix is a greatest-n-per-group pattern. With a window function:
SQL
SELECT department_id, name, salary AS lowest
FROM (
  SELECT e.*, RANK() OVER (PARTITION BY department_id ORDER BY salary) AS rnk
  FROM employees e
  WHERE department_id IS NOT NULL
) AS r
WHERE rnk = 1;
Result
+---------------+-------+-----------+
| department_id | name  | lowest    |
+---------------+-------+-----------+
|             1 | Dev   | 118000.00 |
|             2 | Farid |  95000.00 |
|             3 | Isla  |  72000.00 |
+---------------+-------+-----------+
What’s happening
  1. RANK() … ORDER BY salary (ascending this time) gives the lowest earner in each department rank 1.
  2. Because the whole row is carried through the derived table, name now comes from the same row as the salary: Dev, Farid and Isla.
  3. If two people tied for lowest, RANK would keep both; ROW_NUMBER would keep one arbitrarily.

Learn more: ONLY_FULL_GROUP_BY and GROUP BY.

Open in topic →

Top three salaries per department — RANK, DENSE_RANK or ROW_NUMBER?

"Return the employees who earn one of the top three salaries in their department." Predict the three ranking columns, then say which one answers the question.

SQL
WITH ranked AS (
  SELECT d.name AS department, e.name AS employee, e.salary,
         DENSE_RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) AS dr,
         RANK()       OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) AS rk,
         ROW_NUMBER() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC, e.id) AS rn
  FROM employees e JOIN departments d ON d.id = e.department_id
)
SELECT * FROM ranked WHERE dr <= 3
ORDER BY department, salary DESC, employee;
Show answer

"Top three salaries" means three distinct salary values, so DENSE_RANK() <= 3 is the answer — and in Engineering it returns four people, because Ben and Chloe share second place.

Result
+-------------+----------+-----------+----+----+----+
| department  | employee | salary    | dr | rk | rn |
+-------------+----------+-----------+----+----+----+
| Engineering | Asha     | 185000.00 |  1 |  1 |  1 |
| Engineering | Ben      | 142000.00 |  2 |  2 |  2 |
| Engineering | Chloe    | 142000.00 |  2 |  2 |  3 |
| Engineering | Dev      | 118000.00 |  3 |  4 |  4 |
| Sales       | Elena    | 130000.00 |  1 |  1 |  1 |
| Sales       | Grace    |  99000.00 |  2 |  2 |  2 |
| Sales       | Farid    |  95000.00 |  3 |  3 |  3 |
| Support     | Hiro     |  88000.00 |  1 |  1 |  1 |
| Support     | Isla     |  72000.00 |  2 |  2 |  2 |
+-------------+----------+-----------+----+----+----+
What’s happening
  1. Every function restarts at 1 per department because of PARTITION BY e.department_id.
  2. In Engineering, dr goes 1, 2, 2, 3: Dev's 118,000 is the third distinct salary, so he's in. rk goes 1, 2, 2, 4, so rk <= 3 would drop Dev. rn goes 1, 2, 3, 4, so rn <= 3 would drop Dev too — and would have dropped Chloe instead of Dev if the tiebreaker had been different.
  3. Sales has no ties, so all three functions agree. Support only has two people, so it returns two rows: "top three" is an upper bound, not a promise.
  4. The e.id tiebreaker in the ROW_NUMBER makes its numbering deterministic; without it, which of Ben and Chloe is 2 can change between runs or versions.
  5. The interview point: say the tie policy out loud. "Top 3 people" → ROW_NUMBER. "Top 3 salaries" → DENSE_RANK. "Anyone who'd place in the top 3" (Olympic style) → RANK.

Before window functions: the same answer with a correlated count — "fewer than three distinct salaries in my department are higher than mine":

SQL
SELECT d.name AS department, e.name AS employee, e.salary
FROM employees e JOIN departments d ON d.id = e.department_id
WHERE (SELECT COUNT(DISTINCT e2.salary)
       FROM employees e2
       WHERE e2.department_id = e.department_id
         AND e2.salary > e.salary) < 3
ORDER BY department, e.salary DESC, employee;

It returned the same nine rows as the DENSE_RANK version.

What’s happening
  1. For Dev, the distinct higher salaries in Engineering are 185,000 and 142,000 — a count of 2, which is < 3, so he's in.
  2. For Asha the count is 0; for Ben and Chloe, 1. All in.
  3. This is LeetCode's "Department Top Three Salaries" reference solution. It's correct but runs the subquery once per employee; the window version sorts each department once.

Learn more: ROW_NUMBER, RANK and DENSE_RANK and Top N per group.

Open in topic →

Each customer's most recent order

Show each customer's latest order (id, status, date). Customers who have never ordered should appear with NULLs.

orders (customer_id → id, status, ordered_at)
1 Rohit → 1 shipped 2025-02-01, 2 paid 2025-03-15
2 Maya  → 3 shipped 2025-02-10, 8 shipped 2025-04-05
3 Liam  → 4 cancelled 2025-02-14, 5 shipped 2025-03-01
4 Sofia → 6 pending 2025-03-20
5 Noah  → 7 paid 2025-04-02
6 Zara  → (no orders)
Show answer

A LEFT JOIN LATERAL reads most naturally: "for each customer, fetch their newest order".

SQL
SELECT c.name, o.id AS order_id, o.status, o.ordered_at
FROM customers c
LEFT JOIN LATERAL (
  SELECT id, status, ordered_at
  FROM orders
  WHERE customer_id = c.id
  ORDER BY ordered_at DESC
  LIMIT 1
) AS o ON TRUE
ORDER BY c.id;
Result
+-------+----------+---------+---------------------+
| name  | order_id | status  | ordered_at          |
+-------+----------+---------+---------------------+
| Rohit |        2 | paid    | 2025-03-15 12:30:00 |
| Maya  |        8 | shipped | 2025-04-05 15:40:00 |
| Liam  |        5 | shipped | 2025-03-01 07:45:00 |
| Sofia |        6 | pending | 2025-03-20 21:10:00 |
| Noah  |        7 | paid    | 2025-04-02 13:05:00 |
| Zara  |     NULL | NULL    | NULL                |
+-------+----------+---------+---------------------+
What’s happening
  1. LATERAL lets the derived table refer to c.id from the table to its left — without it, a derived table can't see outer columns. MySQL has supported it since 8.0.14.
  2. For each customer the subquery sorts that customer's orders newest first and keeps one. With an index on (customer_id, ordered_at) that's an index dive per customer, which is very fast when there are few customers and many orders.
  3. LEFT JOIN … ON TRUE keeps customers whose subquery returns nothing, so Zara appears with NULLs. A plain JOIN or comma would drop her.
  4. Changing LIMIT 1 to LIMIT 3 gives each customer's last three orders with no other change — the big advantage of this form.

Alternative 1: ROW_NUMBER():

SQL
SELECT c.name, o.id AS order_id, o.status, o.ordered_at
FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id
                                 ORDER BY ordered_at DESC, id DESC) AS rn
  FROM orders o
) AS o
JOIN customers c ON c.id = o.customer_id
WHERE o.rn = 1
ORDER BY c.id;

This returned the first five rows above — no Zara, because it starts from orders.

What’s happening
  1. The window numbers each customer's orders newest first; rn = 1 is the latest.
  2. id DESC is a tiebreaker in case two orders share a timestamp, so exactly one row per customer comes back.
  3. To include Zara, start from customers and LEFT JOIN the ranked orders with AND o.rn = 1 in the ON clause — putting it in WHERE would filter her out again.
  4. This form scans and numbers every order, which is the better plan when you need most of the table anyway.

Alternative 2: correlated MAX: WHERE o.ordered_at = (SELECT MAX(o2.ordered_at) FROM orders o2 WHERE o2.customer_id = o.customer_id) returned the same five rows. It works on any version, but if two orders share the maximum timestamp it returns both, so it isn't "exactly one per customer" unless the timestamp is unique.

Learn more: Derived tables and LEFT and RIGHT OUTER JOIN.

Open in topic →

Employees who earn more than their department's average

List employees whose salary is above the average salary of their own department, with that average.

Show answer

Asha, Elena and Hiro. A window AVG puts each department's average on every row, so the comparison is a simple filter:

SQL
SELECT name, department_id, salary, ROUND(dept_avg, 2) AS dept_avg
FROM (
  SELECT e.*, AVG(salary) OVER (PARTITION BY department_id) AS dept_avg
  FROM employees e
  WHERE department_id IS NOT NULL
) AS t
WHERE salary > dept_avg
ORDER BY department_id, salary DESC;
Result
+-------+---------------+-----------+-----------+
| name  | department_id | salary    | dept_avg  |
+-------+---------------+-----------+-----------+
| Asha  |             1 | 185000.00 | 146750.00 |
| Elena |             2 | 130000.00 | 108000.00 |
| Hiro  |             3 |  88000.00 |  80000.00 |
+-------+---------------+-----------+-----------+
What’s happening
  1. AVG(salary) OVER (PARTITION BY department_id) has no ORDER BY, so the frame is the whole partition: every Engineering row gets (185000 + 142000 + 142000 + 118000) / 4 = 146750.
  2. The outer WHERE keeps rows above their own department's figure. Ben and Chloe (142,000) are below 146,750, so only Asha survives in Engineering.
  3. Sales averages 108,000 (Elena is above it); Support averages 80,000 (Hiro is above it).
  4. Note the ORDER BY pitfall: AVG(salary) OVER (PARTITION BY department_id ORDER BY salary) would be a running average, not the department average, because adding ORDER BY changes the default frame. See Window frames.

Alternative: correlated subquery (any version):

SQL
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(e2.salary) FROM employees e2
                  WHERE e2.department_id = e.department_id)
ORDER BY e.department_id, e.salary DESC;

It returned the same three people. Jonas drops out on his own here: his department_id is NULL, so e2.department_id = NULL matches nothing, the average is NULL, and salary > NULL is unknown.

What’s happening
  1. For each employee the subquery averages their department. Logically it runs once per outer row, so an index on department_id matters.
  2. It reads naturally and it's what you'd write on 5.7. You can't show the average next to each row without repeating the subquery in the SELECT list, which the window form gives you for free.
  3. A third form joins to a derived table of department_id, AVG(salary) grouped once — usually the most efficient on very old versions.

Learn more: Correlated subqueries and Window functions: OVER and PARTITION BY.

Open in topic →

Customers who bought every book (relational division)

Which customers have bought every product in the Books category (ids 5 and 6), ignoring cancelled orders?

Book purchases (non-cancelled orders)
Rohit: order 2 → products 5 and 6
Liam:  order 5 → product 6
Noah:  order 7 → product 5 (quantity 3)
Show answer

Only Rohit. This is relational division — "find X related to all of Y" — and the standard trick is to count distinct matches per customer and compare with the size of the set:

SQL
SELECT c.name
FROM customers c
JOIN orders o       ON o.customer_id = c.id AND o.status <> 'cancelled'
JOIN order_items oi ON oi.order_id = o.id
JOIN products p     ON p.id = oi.product_id AND p.category_id = 4
GROUP BY c.id, c.name
HAVING COUNT(DISTINCT p.id) = (SELECT COUNT(*) FROM products WHERE category_id = 4);
Result
+-------+
| name  |
+-------+
| Rohit |
+-------+
What’s happening
  1. The joins produce one row per book line bought by each customer: Rohit has two (products 5 and 6), Liam and Noah one each.
  2. COUNT(DISTINCT p.id) counts different books per customer: Rohit 2, Liam 1, Noah 1.
  3. The subquery counts the books that exist: 2. Only Rohit's count equals it.
  4. DISTINCT matters: with COUNT(*), a customer who bought the same book in two separate orders would count 2 and wrongly pass. On this data COUNT(*) happens to give Rohit 2, Liam 1, Noah 1 — the bug is invisible until someone re-orders.

Alternative: double NOT EXISTS — "there is no book this customer hasn't bought":

SQL
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM products p
  WHERE p.category_id = 4
    AND NOT EXISTS (
      SELECT 1 FROM orders o JOIN order_items oi ON oi.order_id = o.id
      WHERE o.customer_id = c.id AND o.status <> 'cancelled'
        AND oi.product_id = p.id));

It also returned only Rohit.

What’s happening
  1. The innermost NOT EXISTS asks "has this customer not bought book p?".
  2. The middle NOT EXISTS asks "is there no such book?" — that is, every book has been bought.
  3. Edge case: if the category is empty, there's no book to be missing, so every customer qualifies. Run against a non-existent category 99, it returned all six customers. The COUNT version would return nobody (no rows to group). Mathematically "bought all of nothing" is true, but say which behaviour you want.
  4. The double negation is harder to read but is the textbook relational-algebra division, and it can stop early per customer.

Learn more: IN vs EXISTS and COUNT(*) vs COUNT(column) vs COUNT(DISTINCT).

Open in topic →

"How do you compute a running total in SQL?"

Show answer

"With a window function: SUM(amount) OVER (ORDER BY date, id), adding PARTITION BY for a running total per customer. I always give the ORDER BY a unique tiebreaker, or specify ROWS UNBOUNDED PRECEDING, because the default frame is RANGE, which treats rows that tie on the order key as one step and gives them all the same total. Before MySQL 8, you'd use a correlated subquery summing all earlier rows — quadratic — or user variables, which are deprecated in expressions now and never had a guaranteed evaluation order."

Open in topic →

Running total of revenue by order date

Add a running_total column to the order totals above, accumulating in date order.

Show answer

SUM() OVER (ORDER BY …) does it in one pass:

SQL
WITH totals AS (
  SELECT o.id, DATE(o.ordered_at) AS day, SUM(oi.quantity * oi.unit_price) AS total
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status <> 'cancelled'
  GROUP BY o.id
)
SELECT id, day, total,
       SUM(total) OVER (ORDER BY day, id) AS running_total
FROM totals
ORDER BY day, id;
Result
+----+------------+---------+---------------+
| id | day        | total   | running_total |
+----+------------+---------+---------------+
|  1 | 2025-02-01 |  957.00 |        957.00 |
|  3 | 2025-02-10 | 1048.00 |       2005.00 |
|  5 | 2025-03-01 |  127.00 |       2132.00 |
|  2 | 2025-03-15 |   88.00 |       2220.00 |
|  6 | 2025-03-20 |  249.00 |       2469.00 |
|  7 | 2025-04-02 | 1016.00 |       3485.00 |
|  8 | 2025-04-05 |  116.00 |       3601.00 |
+----+------------+---------+---------------+
What’s happening
  1. OVER (ORDER BY day, id) sorts the seven rows by date. With an ORDER BY and no explicit frame, each row's frame is "from the first row up to me" (strictly, up to my last peer — see the next question).
  2. SUM(total) over that frame is the running total: 957, then 957 + 1048 = 2005, then 2005 + 127 = 2132, and so on up to 3601.
  3. The last value equals SUM(total) over the whole table, which is a quick sanity check.
  4. id is in the window's ORDER BY as a tiebreaker. No two orders here share a date, but if they did, id would stop them sharing a running total.
  5. Adding PARTITION BY customer_id gives a running total per customer instead: Rohit's two orders run 957 → 1045, Maya's 1048 → 1164.

Before MySQL 8.0, option 1: a correlated subquery that sums every row up to and including the current one:

SQL
WITH totals AS (
  SELECT o.id, DATE(o.ordered_at) AS day, SUM(oi.quantity * oi.unit_price) AS total
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status <> 'cancelled'
  GROUP BY o.id
)
SELECT t1.id, t1.day, t1.total,
       (SELECT SUM(t2.total) FROM totals t2
        WHERE t2.day < t1.day OR (t2.day = t1.day AND t2.id <= t1.id)) AS running_total
FROM totals t1
ORDER BY t1.day, t1.id;

It returned exactly the same seven running totals.

What’s happening
  1. For each row t1, the subquery adds up all rows that come before it in (day, id) order, plus itself.
  2. The OR (t2.day = t1.day AND t2.id <= t1.id) part is the tiebreaker written by hand.
  3. It's O(n²): row 7 re-reads seven rows, row 1,000 re-reads a thousand. Fine for a report over a few hundred rows, painful for a million. (A CTE in a 5.7 answer would be a derived table or a temporary table, since 5.7 has no WITH.)

Before MySQL 8.0, option 2: user variables. You'll still see this in old code:

SQL
SET @run := 0;
SELECT id, paid_on, amount, @run := @run + amount AS running
FROM payments ORDER BY paid_on, id;
SHOW WARNINGS;
Result
+----+------------+--------+---------+
| id | paid_on    | amount | running |
+----+------------+--------+---------+
|  1 | 2025-05-01 | 100.00 |  100.00 |
|  2 | 2025-05-02 |  50.00 |  150.00 |
|  3 | 2025-05-02 |  25.00 |  175.00 |
|  4 | 2025-05-03 |  10.00 |  185.00 |
|  5 | 2025-05-05 |  40.00 |  225.00 |
+----+------------+--------+---------+

+---------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                                                                                                                              |
+---------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Warning | 1287 | Setting user variables within expressions is deprecated and will be removed in a future release. Consider alternatives: 'SET variable=expression, ...', or 'SELECT expression(s) INTO variables(s)'. |
+---------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
What’s happening
  1. @run := @run + amount assigns as each row is produced, so it behaves like a running total — on the small payments table used in the next question it printed 100, 150, 175, 185, 225.
  2. It relies on MySQL evaluating the expression in the final sort order, which the manual has never guaranteed; with joins, GROUP BY or a different plan the order can change.
  3. Since MySQL 8.0.13, assigning a user variable inside an expression raises warning 1287, as shown, still present in 9.7. Treat it as legacy and replace it with a window function.

Learn more: LAG, LEAD and running totals.

Open in topic →

Predict: a running total when two payments share a date

Predict the three running-total columns.

SQL
SELECT id, paid_on, amount,
       SUM(amount) OVER (ORDER BY paid_on)                          AS default_frame,
       SUM(amount) OVER (ORDER BY paid_on ROWS UNBOUNDED PRECEDING) AS rows_frame,
       SUM(amount) OVER (ORDER BY paid_on, id)                      AS tie_broken
FROM payments
ORDER BY paid_on, id;
payments
+----+------------+--------+
| id | paid_on    | amount |
+----+------------+--------+
|  1 | 2025-05-01 | 100.00 |
|  2 | 2025-05-02 |  50.00 |
|  3 | 2025-05-02 |  25.00 |
|  4 | 2025-05-03 |  10.00 |
|  5 | 2025-05-05 |  40.00 |
+----+------------+--------+
Show answer

Payments 2 and 3 both happened on 2 May. With the default frame, both show 175 — the total including both — while the ROWS frame and the tie-broken order give 150, then 175.

Result
+----+------------+--------+---------------+------------+------------+
| id | paid_on    | amount | default_frame | rows_frame | tie_broken |
+----+------------+--------+---------------+------------+------------+
|  1 | 2025-05-01 | 100.00 |        100.00 |     100.00 |     100.00 |
|  2 | 2025-05-02 |  50.00 |        175.00 |     150.00 |     150.00 |
|  3 | 2025-05-02 |  25.00 |        175.00 |     175.00 |     175.00 |
|  4 | 2025-05-03 |  10.00 |        185.00 |     185.00 |     185.00 |
|  5 | 2025-05-05 |  40.00 |        225.00 |     225.00 |     225.00 |
+----+------------+--------+---------------+------------+------------+
What’s happening
  1. With ORDER BY and no frame clause, the SQL standard default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE means "up to the current row and all its peers" — rows with the same paid_on.
  2. For payment 2, its peers are itself and payment 3, so default_frame adds 100 + 50 + 25 = 175. Payment 3 gets the same frame, so also 175. The running total "jumps" over the tied day.
  3. ROWS UNBOUNDED PRECEDING counts physical rows instead, so payment 2 sees only 100 + 50 = 150. But the window orders only by paid_on, so which of 2 and 3 is processed first is up to MySQL — here it was payment 2. The outer ORDER BY doesn't control that; on another plan the two values could swap.
  4. ORDER BY paid_on, id makes the order unique, so there are no peers and the default RANGE frame behaves like ROWS. That's the most robust fix: deterministic and readable.
  5. Which one is "right" depends on the report: a daily balance should show 175 for both 2 May rows (RANGE); a per-transaction statement should show 150 then 175.

Learn more: Window frames.

Open in topic →

A 3-row moving average vs a 3-day moving average

Using the same payments, predict a moving average over "this and the previous two payments" and one over "this day and the previous two days".

SQL
SELECT id, paid_on, amount,
  ROUND(AVG(amount) OVER (ORDER BY paid_on, id
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_last_3_rows,
  ROUND(AVG(amount) OVER (ORDER BY paid_on
        RANGE BETWEEN INTERVAL 2 DAY PRECEDING AND CURRENT ROW), 2) AS avg_last_3_days,
  COUNT(*) OVER (ORDER BY paid_on, id
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS n_rows
FROM payments
ORDER BY paid_on, id;
Show answer

The two columns differ on 2 May, 3 May and 5 May, because 3 rows and 3 days cover different sets of payments when days have two payments or none.

Result
+----+------------+--------+-----------------+-----------------+--------+
| id | paid_on    | amount | avg_last_3_rows | avg_last_3_days | n_rows |
+----+------------+--------+-----------------+-----------------+--------+
|  1 | 2025-05-01 | 100.00 |          100.00 |          100.00 |      1 |
|  2 | 2025-05-02 |  50.00 |           75.00 |           58.33 |      2 |
|  3 | 2025-05-02 |  25.00 |           58.33 |           58.33 |      3 |
|  4 | 2025-05-03 |  10.00 |           28.33 |           46.25 |      3 |
|  5 | 2025-05-05 |  40.00 |           25.00 |           25.00 |      3 |
+----+------------+--------+-----------------+-----------------+--------+
What’s happening
  1. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is a sliding window of up to three physical rows. The first rows have fewer: n_rows shows 1, 2, then 3. Payment 2's average is (100 + 50) / 2 = 75 — an average of two, not three. Decide whether early rows should show a value or NULL (CASE WHEN n_rows = 3 …).
  2. RANGE BETWEEN INTERVAL 2 DAY PRECEDING AND CURRENT ROW is a window over values of paid_on: everything from two days before this row's date up to this date, including peers. For payment 2 (2 May) that's 1–2 May: (100 + 50 + 25) / 3 = 58.33.
  3. Payment 4 (3 May): the 3-row window is payments 2, 3, 4: (50 + 25 + 10) / 3 = 28.33. The 3-day window is 1–3 May, four payments: 185 / 4 = 46.25.
  4. Payment 5 (5 May): the 3-day window is 3–5 May, so it holds payments 4 and 5 only (nothing on 4 May): (10 + 40) / 2 = 25. The 3-row window happens to give (25 + 10 + 40) / 3 = 25 too.
  5. A RANGE frame with an INTERVAL needs a single date or number ORDER BY column, which is why it orders by paid_on alone. For "7-day rolling revenue" on calendar days, use RANGE with an interval; for "last 7 transactions", use ROWS.

Learn more: Window frames.

Open in topic →

Month-over-month revenue change, and days since a customer's previous order

  1. Show monthly revenue with the previous month's revenue and the percentage change.
  2. For each order, how many days passed since that customer's previous order?
Show answer

For part 1, LAG reads the previous row's value in the window order:

SQL
WITH monthly AS (
  SELECT DATE_FORMAT(o.ordered_at, '%Y-%m') AS month,
         SUM(oi.quantity * oi.unit_price) AS revenue
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status <> 'cancelled'
  GROUP BY month
)
SELECT month, revenue, prev,
       ROUND(100 * (revenue - prev) / prev, 1) AS pct_change
FROM (
  SELECT month, revenue, LAG(revenue) OVER w AS prev
  FROM monthly
  WINDOW w AS (ORDER BY month)
) AS t
ORDER BY month;
Result
+---------+---------+---------+------------+
| month   | revenue | prev    | pct_change |
+---------+---------+---------+------------+
| 2025-02 | 2005.00 |    NULL |       NULL |
| 2025-03 |  464.00 | 2005.00 |      -76.9 |
| 2025-04 | 1132.00 |  464.00 |      144.0 |
+---------+---------+---------+------------+
What’s happening
  1. The CTE totals revenue per month: February 957 + 1048 = 2005, March 127 + 88 + 249 = 464, April 1016 + 116 = 1132.
  2. LAG(revenue) OVER w returns the revenue of the row before in month order. February has no row before it, so prev is NULL; LAG(revenue, 1, 0) would give a default of 0 instead.
  3. WINDOW w AS (ORDER BY month) names the window once, so several functions can share it. The derived table means the percentage formula refers to prev rather than repeating LAG(…) three times.
  4. March: 100 × (464 − 2005) / 2005 = −76.9. April: 100 × (1132 − 464) / 464 = 144.0. February stays NULL because any arithmetic with NULL is NULL — usually what you want for "no previous month".
  5. '%Y-%m' strings sort correctly as text because they're zero-padded, year first.

Alternative for part 1: self-join on "the month before". The pre-8.0 form, which also makes a missing month explicit:

SQL
WITH monthly AS (
  SELECT DATE_FORMAT(o.ordered_at, '%Y-%m-01') AS month,
         SUM(oi.quantity * oi.unit_price) AS revenue
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status <> 'cancelled'
  GROUP BY month
)
SELECT cur.month, cur.revenue, prev.revenue AS prev_month
FROM monthly cur
LEFT JOIN monthly prev ON prev.month = cur.month - INTERVAL 1 MONTH
ORDER BY cur.month;
Result
+------------+---------+------------+
| month      | revenue | prev_month |
+------------+---------+------------+
| 2025-02-01 | 2005.00 |       NULL |
| 2025-03-01 |  464.00 |    2005.00 |
| 2025-04-01 | 1132.00 |     464.00 |
+------------+---------+------------+
What’s happening
  1. The month key is now a first-of-month string like '2025-03-01', so cur.month - INTERVAL 1 MONTH is a real date arithmetic expression (MySQL converts the string to a date).
  2. The LEFT JOIN looks for the row whose month is exactly one calendar month earlier, and keeps February with NULL.
  3. The difference from LAG shows when a month has no sales: LAG would compare May with March (the previous row), while the self-join compares May with April and finds nothing. Which is right is a reporting decision — the next question has the same trap with days.

For part 2, partition the LAG by customer and subtract dates:

SQL
SELECT customer_id, id, DATE(ordered_at) AS day,
       DATEDIFF(ordered_at, LAG(ordered_at) OVER (PARTITION BY customer_id
                                                  ORDER BY ordered_at)) AS days_since_prev
FROM orders
ORDER BY customer_id, ordered_at;
Result
+-------------+----+------------+-----------------+
| customer_id | id | day        | days_since_prev |
+-------------+----+------------+-----------------+
|           1 |  1 | 2025-02-01 |            NULL |
|           1 |  2 | 2025-03-15 |              42 |
|           2 |  3 | 2025-02-10 |            NULL |
|           2 |  8 | 2025-04-05 |              54 |
|           3 |  4 | 2025-02-14 |            NULL |
|           3 |  5 | 2025-03-01 |              15 |
|           4 |  6 | 2025-03-20 |            NULL |
|           5 |  7 | 2025-04-02 |            NULL |
+-------------+----+------------+-----------------+
What’s happening
  1. PARTITION BY customer_id makes "previous" mean "this customer's previous order", so Maya's April order looks back to her February order, not to Noah's.
  2. The first order of each customer has no previous row: NULL.
  3. DATEDIFF ignores the time of day and counts calendar days: 1 Feb → 15 Mar is 42. Use TIMESTAMPDIFF(HOUR, …) when the time matters.
  4. Cancelled order 4 is included here on purpose — this is about order activity, not revenue.

Learn more: LAG, LEAD and running totals.

Open in topic →

Days that were warmer than the day before (and the missing-day trap)

Return every date whose temperature was higher than the previous calendar day's. There's no reading for 4 July.

weather
+----+-------------+--------+
| id | recorded_on | temp_c |
+----+-------------+--------+
|  1 | 2025-07-01  |     21 |
|  2 | 2025-07-02  |     24 |
|  3 | 2025-07-03  |     22 |
|  4 | 2025-07-05  |     25 |
|  5 | 2025-07-06  |     23 |
|  6 | 2025-07-07  |     27 |
+----+-------------+--------+
Show answer

The answer is 2 July and 7 July. 5 July must not be returned: its previous calendar day (4 July) has no reading. A self-join on the date expresses "yesterday" exactly:

SQL
SELECT today.recorded_on, today.temp_c, yesterday.temp_c AS yesterday_temp
FROM weather today
JOIN weather yesterday
  ON yesterday.recorded_on = today.recorded_on - INTERVAL 1 DAY
WHERE today.temp_c > yesterday.temp_c;
Result
+-------------+--------+----------------+
| recorded_on | temp_c | yesterday_temp |
+-------------+--------+----------------+
| 2025-07-02  |     24 |             21 |
| 2025-07-07  |     27 |             23 |
+-------------+--------+----------------+
What’s happening
  1. For each row today, the join finds the row dated exactly one day earlier. 2 July pairs with 1 July; 3 July with 2 July.
  2. 5 July looks for 4 July, finds nothing, and the inner join drops it — correct, since there's nothing to compare with.
  3. The WHERE keeps pairs where today is warmer: 24 > 21 (2 July) and 27 > 23 (7 July). 3 July (22 < 24) and 6 July (23 < 25) fail.
  4. With an index on recorded_on (it's UNIQUE here), each lookup is a single index probe.

The tempting LAG version is subtly wrong:

SQL
SELECT recorded_on, temp_c
FROM (
  SELECT recorded_on, temp_c, LAG(temp_c) OVER (ORDER BY recorded_on) AS prev_temp
  FROM weather
) AS t
WHERE temp_c > prev_temp;
Result
+-------------+--------+
| recorded_on | temp_c |
+-------------+--------+
| 2025-07-02  |     24 |
| 2025-07-05  |     25 |
| 2025-07-07  |     27 |
+-------------+--------+
What’s happening
  1. LAG returns the previous row, not the previous day. For 5 July the previous row is 3 July (22), so 25 > 22 and it's returned.
  2. On data with no gaps, LAG and the self-join agree — which is why the bug survives testing.
  3. The fix keeps LAG but checks that the previous row really is yesterday: also take LAG(recorded_on) OVER w AS prev_day and add AND prev_day = recorded_on - INTERVAL 1 DAY. Run that way it returned 2 July and 7 July only.
  4. A third bug you'll see is joining on w1.id = w2.id + 1. It assumes ids are consecutive and in date order. Here ids have no gap, so it compared 5 July with 3 July and returned the same three rows as the plain LAG.

Learn more: LAG, LEAD and running totals and Self joins.

Open in topic →

"What's the gaps-and-islands technique?"

Show answer

"Islands are runs of consecutive values. I number the rows with ROW_NUMBER() in value order and subtract the row number from the value — or subtract that many days from a date. Within a run the difference is constant, so it becomes a group key: GROUP BY it to get each run's start, end and length. For runs of equal values, like status changes, I flag each row where the value differs from LAG(value) and take a running SUM of the flags as the group number. Gaps are the reverse: LEAD(id) minus id greater than one marks a gap, or I generate the full sequence with a recursive CTE and anti-join to find what's missing."

Open in topic →

Find the missing ticket numbers — as ranges and as a list

  1. Return each gap as a range (gap_start, gap_end).
  2. Return every missing id individually, up to the highest id.
Show answer

For part 1, compare each id with the next one using LEAD:

SQL
SELECT id + 1 AS gap_start, next_id - 1 AS gap_end
FROM (
  SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id
  FROM tickets
) AS t
WHERE next_id - id > 1;
Result
+-----------+---------+
| gap_start | gap_end |
+-----------+---------+
|         4 |       4 |
|         7 |       8 |
|        12 |      14 |
+-----------+---------+
What’s happening
  1. LEAD(id) OVER (ORDER BY id) gives each row the next id: 1 → 2, 3 → 5, 6 → 9, 11 → 15, and 15 → NULL.
  2. Where the step is more than 1, there's a gap: 3 → 5 skips 4, 6 → 9 skips 7–8, 11 → 15 skips 12–14.
  3. The gap starts one after the current id and ends one before the next id.
  4. The last row has next_id = NULL, so NULL - 15 > 1 is unknown and it's filtered out — no special case needed.
  5. One sort, one pass: this is the form to use on MySQL 8.0+.

Alternative for part 1 (any version): a row starts a gap if id + 1 doesn't exist, and the gap ends just before the next existing id:

SQL
SELECT t.id + 1 AS gap_start,
       (SELECT MIN(t3.id) - 1 FROM tickets t3 WHERE t3.id > t.id) AS gap_end
FROM tickets t
WHERE NOT EXISTS (SELECT 1 FROM tickets t2 WHERE t2.id = t.id + 1)
  AND t.id < (SELECT MAX(id) FROM tickets);

It returned the same three ranges.

What’s happening
  1. NOT EXISTS (… t2.id = t.id + 1) keeps ids whose successor is missing: 3, 6, 11 and 15.
  2. t.id < MAX(id) removes 15 — after the highest id there's no gap, just the end of the data.
  3. The scalar subquery finds the next existing id (5, 9, 15) and subtracts one.
  4. With the primary key index, each probe is cheap, but there are two correlated lookups per row.

For part 2, generate every number from 1 to the maximum with a recursive CTE and keep the ones that don't exist:

SQL
WITH RECURSIVE seq AS (
  SELECT 1 AS n
  UNION ALL
  SELECT n + 1 FROM seq WHERE n < (SELECT MAX(id) FROM tickets)
)
SELECT n AS missing_id
FROM seq LEFT JOIN tickets t ON t.id = seq.n
WHERE t.id IS NULL;
Result
+------------+
| missing_id |
+------------+
|          4 |
|          7 |
|          8 |
|         12 |
|         13 |
|         14 |
+------------+
What’s happening
  1. The anchor SELECT 1 AS n produces the first row; the recursive part adds n + 1 until n reaches 15. The CTE holds 1 … 15.
  2. The LEFT JOIN … WHERE t.id IS NULL is an anti-join: numbers with no matching ticket.
  3. This lists every missing id, which the range queries don't. It's also the pattern for a calendar of dates (next questions).
  4. Recursion is capped by cte_max_recursion_depth (default 1000), so a sequence of more than about a thousand numbers needs the limit raised — the calendar question shows the real error.

Learn more: Recursive CTEs and LAG, LEAD and running totals.

Open in topic →

Turn the ticket ids into ranges (islands) — and why might it fail on other data?

Using the grp column from the introduction, return each run of consecutive ids with its start, end and size. Then explain why id - ROW_NUMBER() OVER (ORDER BY id) can error on a table whose ids start at 0 or below.

Show answer

Group by the difference:

SQL
SELECT MIN(id) AS range_start, MAX(id) AS range_end, COUNT(*) AS size
FROM (
  SELECT id, id - ROW_NUMBER() OVER (ORDER BY id) AS grp
  FROM tickets
) AS t
GROUP BY grp
ORDER BY range_start;
Result
+-------------+-----------+------+
| range_start | range_end | size |
+-------------+-----------+------+
|           1 |         3 |    3 |
|           5 |         6 |    2 |
|           9 |        11 |    3 |
|          15 |        15 |    1 |
+-------------+-----------+------+
What’s happening
  1. The derived table labels each id with its island key: 0, 0, 0, 1, 1, 3, 3, 3, 6.
  2. GROUP BY grp collapses each island; MIN and MAX are its ends and COUNT(*) its length.
  3. A single isolated id (15) is an island of size 1 — gaps and islands are two views of the same data.
  4. The ORDER BY range_start is needed: GROUP BY doesn't promise any output order in MySQL 8.0+.

The error: ROW_NUMBER() returns BIGINT UNSIGNED, and MySQL won't let an unsigned subtraction go below zero:

SQL
SELECT 0 - ROW_NUMBER() OVER () AS x;
Result
ERROR 1690 (22003): BIGINT UNSIGNED value is out of range in '(0 - row_number() OVER () )'
What’s happening
  1. CREATE TABLE … AS SELECT ROW_NUMBER() OVER () AS rn shows the type: bigint unsigned NOT NULL.
  2. When one operand of - is unsigned, MySQL does unsigned arithmetic, so 0 - 1 is out of range instead of -1.
  3. On the tickets data id >= rn always holds, so it never fires. With ids starting at 0, or when grouping by equal values inside a partition (the next question), the difference can go negative.
  4. The fix is to cast: CAST(id AS SIGNED) - CAST(ROW_NUMBER() OVER (…) AS SIGNED), or enable the NO_UNSIGNED_SUBTRACTION SQL mode. PostgreSQL's row_number() returns a signed bigint, so this is a MySQL-specific trap.

Learn more: Window functions: OVER and PARTITION BY and Numeric types: INT, DECIMAL and FLOAT.

Open in topic →

Longest login streak per user

Find each user's streaks of consecutive login days, then each user's longest streak.

logins (user_id, login_on)
user 1: 2025-06-01, 06-02, 06-03, 06-05, 06-06
user 2: 2025-06-01, 06-03, 06-04, 06-05, 06-06
user 3: 2025-06-02
Show answer

User 1's longest streak is 3 days, user 2's 4 days, user 3's 1 day. Subtract the row number in days from each date to get a constant per streak:

SQL
WITH grouped AS (
  SELECT user_id, login_on,
         DATE_SUB(login_on, INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id
                                                       ORDER BY login_on) DAY) AS grp
  FROM logins
)
SELECT user_id, MIN(login_on) AS streak_start, MAX(login_on) AS streak_end, COUNT(*) AS days
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, streak_start;
Result
+---------+--------------+------------+------+
| user_id | streak_start | streak_end | days |
+---------+--------------+------------+------+
|       1 | 2025-06-01   | 2025-06-03 |    3 |
|       1 | 2025-06-05   | 2025-06-06 |    2 |
|       2 | 2025-06-01   | 2025-06-01 |    1 |
|       2 | 2025-06-03   | 2025-06-06 |    4 |
|       3 | 2025-06-02   | 2025-06-02 |    1 |
+---------+--------------+------------+------+
What’s happening
  1. PARTITION BY user_id numbers each user's logins separately, in date order: user 1's are 1 … 5.
  2. Subtracting that many days: 1 June − 1 = 31 May, 2 June − 2 = 31 May, 3 June − 3 = 31 May, then 5 June − 4 = 1 June, 6 June − 5 = 1 June. Same date = same streak.
  3. GROUP BY user_id, grp gives one row per streak; COUNT(*) is its length. The grp date itself is meaningless — it's just a label.
  4. Date subtraction with DATE_SUB returns a DATE, so the unsigned-integer trap from the previous question doesn't apply here.
  5. The (user_id, login_on) primary key guarantees one row per user per day. If a user could log in twice on the same day, deduplicate first (SELECT DISTINCT user_id, DATE(logged_in_at)), or the second login would get its own row number and break the streak.

For the longest streak per user, aggregate once more:

SQL
WITH grouped AS (
  SELECT user_id, login_on,
         DATE_SUB(login_on, INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id
                                                       ORDER BY login_on) DAY) AS grp
  FROM logins
), streaks AS (
  SELECT user_id, COUNT(*) AS days FROM grouped GROUP BY user_id, grp
)
SELECT user_id, MAX(days) AS longest_streak FROM streaks GROUP BY user_id;
Result
+---------+----------------+
| user_id | longest_streak |
+---------+----------------+
|       1 |              3 |
|       2 |              4 |
|       3 |              1 |
+---------+----------------+
What’s happening
  1. streaks is the previous result without the dates: one row per streak with its length.
  2. MAX(days) per user picks the longest.
  3. Chaining CTEs like this keeps each step testable on its own — a good habit to narrate in an interview.

Alternative: flag the starts and count them. A streak starts wherever the gap since the previous login isn't exactly one day; a running SUM of those flags numbers the streaks:

SQL
WITH flagged AS (
  SELECT user_id, login_on,
         CASE WHEN DATEDIFF(login_on, LAG(login_on) OVER (PARTITION BY user_id
                                                          ORDER BY login_on)) = 1
              THEN 0 ELSE 1 END AS new_streak
  FROM logins
), numbered AS (
  SELECT user_id, login_on,
         SUM(new_streak) OVER (PARTITION BY user_id ORDER BY login_on) AS streak_no
  FROM flagged
)
SELECT user_id, streak_no, MIN(login_on) AS streak_start, COUNT(*) AS days
FROM numbered
GROUP BY user_id, streak_no
ORDER BY user_id, streak_no;

It returned the same five streaks, numbered 1, 2 for users 1 and 2 and 1 for user 3.

What’s happening
  1. LAG(login_on) is the user's previous login. The first login has NULL, DATEDIFF is NULL, NULL = 1 is unknown, so CASE takes the ELSE branch: a new streak.
  2. A one-day difference continues the streak (0); anything else starts one (1).
  3. The running SUM turns the flags 1, 0, 0, 1, 0 into streak numbers 1, 1, 1, 2, 2.
  4. This form is more flexible than the subtraction trick: change = 1 to <= 2 and a one-day break no longer ends a streak, which the arithmetic trick can't express.

Learn more: LAG, LEAD and running totals.

Open in topic →

Numbers that appear at least three times in a row

Find every num that appears in at least three consecutive rows (by id).

readings
+----+-----+
| id | num |
+----+-----+
|  1 |   1 |
|  2 |   1 |
|  3 |   1 |
|  4 |   2 |
|  5 |   1 |
|  6 |   2 |
|  7 |   2 |
|  8 |   2 |
|  9 |   2 |
| 10 |   3 |
+----+-----+
Show answer

1 and 2. The 1s at ids 1–3 are a run of three; the 2s at ids 6–9 a run of four. (The single 2 at id 4 and the 1 at id 5 don't count.) The classic answer is a three-way self-join:

SQL
SELECT DISTINCT r1.num AS consecutive_num
FROM readings r1
JOIN readings r2 ON r2.id = r1.id + 1 AND r2.num = r1.num
JOIN readings r3 ON r3.id = r1.id + 2 AND r3.num = r1.num;
Result
+-----------------+
| consecutive_num |
+-----------------+
|               1 |
|               2 |
+-----------------+
What’s happening
  1. Each r1 row looks for the next two rows by id and requires the same num.
  2. r1.id = 1 finds ids 2 and 3, both 1: a match. r1.id = 6 finds 7 and 8, all 2: a match; so does r1.id = 7 (8 and 9).
  3. The run of four 2s matches twice, so DISTINCT is needed to return 2 once.
  4. It assumes ids have no gaps. If id 7 had been deleted, ids 6 and 8 would be "consecutive" rows but r1.id + 1 wouldn't find anything.

Alternative 1: LAG twice — compare each row with the two before it in id order, which also tolerates gaps in the ids:

SQL
SELECT DISTINCT num AS consecutive_num
FROM (
  SELECT num,
         LAG(num, 1) OVER (ORDER BY id) AS prev1,
         LAG(num, 2) OVER (ORDER BY id) AS prev2
  FROM readings
) AS t
WHERE num = prev1 AND num = prev2;

It returned 1 and 2.

What’s happening
  1. LAG(num, 2) reaches two rows back. For id 3: num = 1, prev1 = 1, prev2 = 1 → match.
  2. For ids 8 and 9, the two rows before are both 2 → two matches, collapsed by DISTINCT.
  3. Changing "three" to "five" means adding more LAG columns — fine for a fixed small N, clumsy beyond that.

Alternative 2: islands of equal values — gives each run's length directly, so "at least N" is a HAVING:

SQL
SELECT num, MIN(id) AS from_id, MAX(id) AS to_id, COUNT(*) AS run_length
FROM (
  SELECT id, num,
         CAST(id AS SIGNED)
       - CAST(ROW_NUMBER() OVER (PARTITION BY num ORDER BY id) AS SIGNED) AS grp
  FROM readings
) AS t
GROUP BY num, grp
HAVING COUNT(*) >= 3;
Result
+-----+---------+-------+------------+
| num | from_id | to_id | run_length |
+-----+---------+-------+------------+
|   1 |       1 |     3 |          3 |
|   2 |       6 |     9 |          4 |
+-----+---------+-------+------------+
What’s happening
  1. Numbering within each value (PARTITION BY num): the 1s at ids 1, 2, 3, 5 get 1, 2, 3, 4; the 2s at ids 4, 6, 7, 8, 9 get 1, 2, 3, 4, 5.
  2. id - rn is constant within a run: the 1s give 0, 0, 0, 1 (ids 1–3 are one island, id 5 another); the 2s give 3, 4, 4, 4, 4.
  3. The CASTs are needed because this subtraction would otherwise be unsigned — here it doesn't go negative, but casting is the safe habit.
  4. HAVING COUNT(*) >= 3 keeps runs of three or more, and you get where each run starts and ends for free. This scales to any N, and it's still ids-must-be-gap-free; for gap-tolerant runs use ROW_NUMBER() OVER (ORDER BY id) in place of id.

Learn more: Self joins and ROW_NUMBER, RANK and DENSE_RANK.

Open in topic →

Orders per day including the days with none — spot the bug

A report must list every day from 14 to 21 March 2025 with its number of orders, showing 0 on days without orders. This attempt returns 1 for every day. Why, and what's the fix?

SQL
WITH RECURSIVE calendar AS (
  SELECT DATE '2025-03-14' AS day
  UNION ALL
  SELECT day + INTERVAL 1 DAY FROM calendar WHERE day < '2025-03-21'
)
SELECT c.day, COUNT(*) AS orders
FROM calendar c
LEFT JOIN orders o ON DATE(o.ordered_at) = c.day
GROUP BY c.day
ORDER BY c.day;
Show answer

COUNT(*) counts rows, and a LEFT JOIN produces one row for a day with no match — the calendar row with NULLs on the order side. On this data each day has at most one order, so every day comes out as 1. Count a column from the right-hand table instead:

SQL
WITH RECURSIVE calendar AS (
  SELECT DATE '2025-03-14' AS day
  UNION ALL
  SELECT day + INTERVAL 1 DAY FROM calendar WHERE day < '2025-03-21'
)
SELECT c.day, COUNT(o.id) AS orders
FROM calendar c
LEFT JOIN orders o
  ON o.ordered_at >= c.day
 AND o.ordered_at <  c.day + INTERVAL 1 DAY
GROUP BY c.day
ORDER BY c.day;
Result
+------------+--------+
| day        | orders |
+------------+--------+
| 2025-03-14 |      0 |
| 2025-03-15 |      1 |
| 2025-03-16 |      0 |
| 2025-03-17 |      0 |
| 2025-03-18 |      0 |
| 2025-03-19 |      0 |
| 2025-03-20 |      1 |
| 2025-03-21 |      0 |
+------------+--------+
What’s happening
  1. The recursive CTE generates the eight dates. The anchor is a DATE literal, so the column is a DATE and day + INTERVAL 1 DAY stays a date.
  2. The LEFT JOIN keeps every calendar day. 15 March matches order 2 and 20 March matches order 6; the other six days get one row with o.* all NULL.
  3. COUNT(o.id) ignores NULLs, so empty days count 0. COUNT(*) counted the NULL-padded row as 1 — that was the bug.
  4. The join condition is also rewritten as a half-open range on ordered_at instead of DATE(o.ordered_at) = c.day. Both give the same answer, but wrapping the column in DATE() stops MySQL using an index on ordered_at; the range form can.
  5. This "generate the calendar, then LEFT JOIN the facts" shape is how every gap-free report is built. Many schemas keep a permanent calendar table for it.

The recursion limit. Generating three years of days hits MySQL's default cap of 1,000 recursion steps:

SQL
WITH RECURSIVE calendar AS (
  SELECT DATE '2025-01-01' AS day
  UNION ALL
  SELECT day + INTERVAL 1 DAY FROM calendar WHERE day < '2027-12-31'
)
SELECT COUNT(*) FROM calendar;
Result
ERROR 3636 (HY000): Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.
What’s happening
  1. 2025-01-01 to 2027-12-31 is 1,095 days, which needs more than 1,000 recursive steps.
  2. cte_max_recursion_depth (default 1000) is a safety net against runaway recursion, such as a missing or wrong stop condition.
  3. After SET SESSION cte_max_recursion_depth = 2000; the same query returned 1095.
  4. For long ranges, a permanent calendar table (or a cross join of digit tables) avoids recursion entirely.

Learn more: Recursive CTEs and COUNT(*) vs COUNT(column) vs COUNT(DISTINCT).

Open in topic →

Group server checks into up and down periods

Collapse these checks into periods: each period is a run of the same status, with its first and last check time.

server_checks
+---------------------+--------+
| checked_at          | status |
+---------------------+--------+
| 2025-08-01 10:00:00 | up     |
| 2025-08-01 10:05:00 | up     |
| 2025-08-01 10:10:00 | down   |
| 2025-08-01 10:15:00 | down   |
| 2025-08-01 10:20:00 | up     |
| 2025-08-01 10:25:00 | down   |
| 2025-08-01 10:30:00 | up     |
| 2025-08-01 10:35:00 | up     |
+---------------------+--------+
Show answer

There are five periods: up, down, up, down, up. A plain GROUP BY status would wrongly merge them into two rows. Flag every change and take a running sum to number the periods:

SQL
WITH flagged AS (
  SELECT checked_at, status,
         CASE WHEN status = LAG(status) OVER (ORDER BY checked_at) THEN 0 ELSE 1 END AS changed
  FROM server_checks
), periods AS (
  SELECT checked_at, status,
         SUM(changed) OVER (ORDER BY checked_at) AS period_no
  FROM flagged
)
SELECT period_no, status, MIN(checked_at) AS first_check,
       MAX(checked_at) AS last_check, COUNT(*) AS checks
FROM periods
GROUP BY period_no, status
ORDER BY period_no;
Result
+-----------+--------+---------------------+---------------------+--------+
| period_no | status | first_check         | last_check          | checks |
+-----------+--------+---------------------+---------------------+--------+
|         1 | up     | 2025-08-01 10:00:00 | 2025-08-01 10:05:00 |      2 |
|         2 | down   | 2025-08-01 10:10:00 | 2025-08-01 10:15:00 |      2 |
|         3 | up     | 2025-08-01 10:20:00 | 2025-08-01 10:20:00 |      1 |
|         4 | down   | 2025-08-01 10:25:00 | 2025-08-01 10:25:00 |      1 |
|         5 | up     | 2025-08-01 10:30:00 | 2025-08-01 10:35:00 |      2 |
+-----------+--------+---------------------+---------------------+--------+
What’s happening
  1. LAG(status) is the previous check's status. The CASE produces changed = 1 where the status differs from the previous one, and also on the first row, where LAG is NULL. The flags are 1, 0, 1, 0, 1, 1, 1, 0.
  2. The running SUM(changed) OVER (ORDER BY checked_at) turns those into period numbers 1, 1, 2, 2, 3, 4, 5, 5. Every change increments the counter; repeats leave it alone.
  3. GROUP BY period_no, status collapses each period. status is in the GROUP BY only so it can be shown — it's constant within a period.
  4. The arithmetic trick (value minus row number) can't do this, because statuses aren't numbers that go up by one. The "flag and sum" trick works for any value you can compare.
  5. To get durations, use LEAD(first_check) OVER (ORDER BY period_no) as each period's end — a period lasts until the next one begins, not until its own last check.

Learn more: LAG, LEAD and running totals and CASE expressions.

Open in topic →

"How do you query a hierarchy stored as parent ids?"

Show answer

"For one level, a self-join: join the table to itself on child.parent_id = parent.id, with a LEFT JOIN if the root should appear. For any depth, a recursive CTE — available since MySQL 8.0: an anchor that selects the starting rows, UNION ALL, and a recursive part that joins the table to the CTE. I carry a depth counter and a path string, cast wide in the anchor because the anchor fixes the column types. If the data might contain a cycle, I either keep a visited list in the path and stop when I see a repeat, or use UNION DISTINCT; MySQL also aborts after cte_max_recursion_depth iterations, 1000 by default. On 5.7 there's no recursion, so you'd self-join a fixed number of levels or store a closure table or nested sets."

Open in topic →

Employees who earn more than their manager

Return the names of employees who earn more than their direct manager.

staff
+----+-------+--------+------------+
| id | name  | salary | manager_id |
+----+-------+--------+------------+
|  1 | Joe   |  70000 |          3 |
|  2 | Henry |  80000 |          4 |
|  3 | Sam   |  60000 |       NULL |
|  4 | Max   |  90000 |       NULL |
|  5 | Ana   |  65000 |          3 |
+----+-------+--------+------------+
Show answer

Joe and Ana — both report to Sam, who earns 60,000. Join the table to itself, once as the employee and once as the manager:

SQL
SELECT e.name AS employee
FROM staff e
JOIN staff m ON m.id = e.manager_id
WHERE e.salary > m.salary;
Result
+----------+
| employee |
+----------+
| Joe      |
| Ana      |
+----------+
What’s happening
  1. staff e is the employee copy and staff m the manager copy. The aliases are mandatory: without them MySQL can't tell which salary you mean.
  2. ON m.id = e.manager_id pairs each employee with their manager's row: Joe–Sam, Henry–Max, Ana–Sam.
  3. Sam and Max have no manager. Their manager_id is NULL, which matches no id, so the inner join drops them — correct, since they can't out-earn a manager they don't have.
  4. The WHERE compares the two copies' salaries: Joe 70,000 > Sam 60,000 and Ana 65,000 > 60,000 pass; Henry 80,000 < Max 90,000 doesn't.

Alternative: correlated subquery:

SQL
SELECT e.name AS employee
FROM staff e
WHERE e.salary > (SELECT m.salary FROM staff m WHERE m.id = e.manager_id);

It returned Joe and Ana too.

What’s happening
  1. For each employee, the subquery fetches one value: the manager's salary.
  2. For Sam and Max it finds no row, so the scalar subquery is NULL, salary > NULL is unknown, and they're filtered out — the same result as the inner join, for a different reason.
  3. The join is the usual answer because it can also show the manager's name and salary in the output; the subquery can only test.

On the site's own employees table the same self-join returns Empty set: nobody out-earns their manager (Dev's 118,000 is below Ben's 142,000; Grace's 99,000 is below Elena's 130,000). Always check the empty case is really empty — a wrong join condition also returns nothing.

Learn more: Self joins.

Open in topic →

Managers with at least two direct reports — and everyone with their manager's name

  1. List every employee with their manager's name, showing (no manager) for the top of the tree.
  2. List the managers who have at least two direct reports, with the count.
Show answer

For part 1, a LEFT self-join keeps the employee who has no manager:

SQL
SELECT e.name AS employee, COALESCE(m.name, '(no manager)') AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.id;
Result
+----------+--------------+
| employee | manager      |
+----------+--------------+
| Asha     | (no manager) |
| Ben      | Asha         |
| Chloe    | Asha         |
| Dev      | Ben          |
| Elena    | Asha         |
| Farid    | Elena        |
| Grace    | Elena        |
| Hiro     | Asha         |
| Isla     | Hiro         |
| Jonas    | Asha         |
+----------+--------------+
What’s happening
  1. Every employee is kept because they're on the left of a LEFT JOIN.
  2. Asha's manager_id is NULL, so no manager row matches and m.name is NULL. With an inner join she'd vanish — the classic bug in this question.
  3. COALESCE(m.name, '(no manager)') replaces that NULL with a label for display.

For part 2, join employees to their managers and group by the manager:

SQL
SELECT m.name AS manager, COUNT(*) AS direct_reports
FROM employees e
JOIN employees m ON m.id = e.manager_id
GROUP BY m.id, m.name
HAVING COUNT(*) >= 2
ORDER BY direct_reports DESC;
Result
+---------+----------------+
| manager | direct_reports |
+---------+----------------+
| Asha    |              5 |
| Elena   |              2 |
+---------+----------------+
What’s happening
  1. The join produces one row per (employee, manager) pair: nine rows, because Asha has no manager.
  2. Grouping by the manager counts their direct reports: Asha 5 (Ben, Chloe, Elena, Hiro, Jonas), Elena 2, Ben 1, Hiro 1.
  3. HAVING COUNT(*) >= 2 keeps Asha and Elena.
  4. Grouping by m.id as well as m.name matters if two managers could share a name; MySQL accepts m.name in the SELECT because it's functionally dependent on m.id.

The shorter version without a join is SELECT name FROM employees WHERE id IN (SELECT manager_id FROM employees GROUP BY manager_id HAVING COUNT(*) >= 2), which returned Asha and Elena — but it can't show the count. (Here IN is safe even though manager_id has a NULL: the NULL group has only one row, so it's removed by HAVING, and IN with a NULL only causes trouble under NOT IN.)

Learn more: Self joins and HAVING vs WHERE.

Open in topic →

Spot the bug: the recursive path that fails with "Data too long"

This recursive CTE labels the root 'CEO' and appends names. It fails. Why?

SQL
WITH RECURSIVE org AS (
  SELECT id, 'CEO' AS title_path FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, CONCAT(org.title_path, ' > ', e.name)
  FROM employees e JOIN org ON e.manager_id = org.id
)
SELECT * FROM org;
Show answer

The anchor fixes the column types. 'CEO' is a three-character string, so title_path becomes a column that holds three characters, and the first recursive row ('CEO > Ben') doesn't fit:

Result
ERROR 1406 (22001): Data too long for column 'title_path' at row 1
What’s happening
  1. MySQL works out a recursive CTE's column types from the anchor (non-recursive) part only. A literal 'CEO' gives VARCHAR(3).
  2. The recursive part produces CONCAT('CEO', ' > ', 'Ben'), nine characters, for a column that holds three.
  3. In strict SQL mode (the default) that's an error. With strict mode off it's worse: run with sql_mode = '', the query succeeded and every row's title_path was just CEO — truncated, and SHOW WARNINGS was empty, so nothing told us.
  4. The fix is to give the anchor room: CAST('CEO' AS CHAR(500)) AS title_path. That's why the org-chart query at the top of this topic casts name to CHAR(200).
  5. It "worked" when the anchor was name because name is VARCHAR(50) and these paths are under 50 characters. It would break on a deeper tree — a time bomb, so cast anyway.

The same rule explains a quieter bug: an integer counter like 0 AS depth gets a small integer type, which is fine for depth but not for, say, a running product that grows quickly. Cast in the anchor whenever the recursive part can grow a value.

Learn more: Recursive CTEs.

Open in topic →

Isla's chain of command, and the total team under each manager

  1. List Isla's management chain up to the top, nearest manager first.
  2. For every manager, count all the people below them (direct and indirect) and their total salary.
Show answer

For part 1, walk upwards: the anchor is Isla, and each step joins to the previous row's manager:

SQL
WITH RECURSIVE chain AS (
  SELECT id, name, manager_id, 0 AS level
  FROM employees WHERE name = 'Isla'
  UNION ALL
  SELECT m.id, m.name, m.manager_id, chain.level + 1
  FROM employees m JOIN chain ON m.id = chain.manager_id
)
SELECT level, name FROM chain ORDER BY level;
Result
+-------+------+
| level | name |
+-------+------+
|     0 | Isla |
|     1 | Hiro |
|     2 | Asha |
+-------+------+
What’s happening
  1. The anchor selects Isla at level 0. Her manager_id is 8 (Hiro).
  2. The recursive step joins on m.id = chain.manager_id — the reverse direction of the org chart — and finds Hiro at level 1. Hiro's manager is Asha, found at level 2.
  3. Asha's manager_id is NULL, so the next step matches nothing and recursion stops.
  4. Going up is always a single chain (each person has one manager), so it's cheap; going down fans out.

For part 2, generate every (manager, report) pair at any depth, then aggregate:

SQL
WITH RECURSIVE reports AS (
  SELECT manager_id AS boss_id, id AS report_id
  FROM employees WHERE manager_id IS NOT NULL
  UNION ALL
  SELECT r.boss_id, e.id
  FROM reports r JOIN employees e ON e.manager_id = r.report_id
)
SELECT b.name AS manager, COUNT(*) AS all_reports, SUM(e.salary) AS team_salary
FROM reports r
JOIN employees b ON b.id = r.boss_id
JOIN employees e ON e.id = r.report_id
GROUP BY b.id, b.name
ORDER BY all_reports DESC, manager;
Result
+---------+-------------+-------------+
| manager | all_reports | team_salary |
+---------+-------------+-------------+
| Asha    |           9 |   977000.00 |
| Elena   |           2 |   194000.00 |
| Ben     |           1 |   118000.00 |
| Hiro    |           1 |    72000.00 |
+---------+-------------+-------------+
What’s happening
  1. The anchor produces every direct pair: (Asha, Ben), (Asha, Chloe), (Ben, Dev), (Elena, Farid)… nine pairs.
  2. The recursive step keeps the boss and moves the report one level down: (Asha, Ben) + Ben's report Dev → (Asha, Dev). That's how Asha collects her indirect reports.
  3. After two levels nothing new appears. Asha ends with 9 pairs — everyone except herself.
  4. The joins look up names and salaries; SUM(e.salary) is the cost of each manager's whole team (not including the manager): Asha's is the other nine salaries, 977000.
  5. This is a transitive closure. Some schemas store it permanently as a "closure table" (ancestor_id, descendant_id, depth) so these questions become simple joins without recursion.

Learn more: Recursive CTEs.

Open in topic →

All products under Electronics, at any depth

"List every product in the Electronics category." Why does the obvious join return nothing, and what's the correct query?

categories
+----+-------------+-----------+
| id | name        | parent_id |
+----+-------------+-----------+
|  1 | Electronics |      NULL |
|  2 | Laptops     |         1 |
|  3 | Phones      |         1 |
|  4 | Books       |      NULL |
|  5 | Accessories |         1 |
+----+-------------+-----------+
Show answer

No product is assigned to Electronics directly — they're all in its subcategories — so SELECT p.name FROM products p JOIN categories c ON c.id = p.category_id WHERE c.name = 'Electronics' returns Empty set. Collect the category subtree first, then join products to it:

SQL
WITH RECURSIVE tree AS (
  SELECT id, name FROM categories WHERE name = 'Electronics'
  UNION ALL
  SELECT c.id, c.name FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT t.name AS category, p.name AS product, p.price
FROM tree t
JOIN products p ON p.category_id = t.id
ORDER BY t.name, p.price DESC;
Result
+-------------+-----------------------------+---------+
| category    | product                     | price   |
+-------------+-----------------------------+---------+
| Accessories | Noise-cancelling Headphones |  249.00 |
| Accessories | USB-C Charger               |   29.00 |
| Laptops     | MacBook Air                 | 1299.00 |
| Laptops     | ThinkBook 14                |  899.00 |
| Phones      | iPhone 17                   | 1099.00 |
| Phones      | Pixel 10                    |  799.00 |
+-------------+-----------------------------+---------+
What’s happening
  1. The anchor finds Electronics (id 1).
  2. The recursive step finds its children: Laptops, Phones and Accessories. None of them has children, so the next step is empty and the CTE holds four categories.
  3. Joining products to all four returns the six Electronics products, including the iPhone with zero stock — the query asks about category, not availability.
  4. If a "Gaming laptops" category were later added under Laptops, this query would include it with no change. A non-recursive WHERE c.id = 1 OR c.parent_id = 1 would miss it — that's the point of recursion.

Learn more: Recursive CTEs and Joining more than two tables.

Open in topic →

A cycle in the tree — what happens, and how do you guard against it?

Someone sets B's parent to D, creating the loop B → C → D → B. Predict what this recursive walk from B does, and write a version that stops.

SQL
WITH RECURSIVE walk AS (
  SELECT id, name, parent_id FROM links WHERE id = 2
  UNION ALL
  SELECT l.id, l.name, l.parent_id
  FROM links l JOIN walk w ON l.parent_id = w.id
)
SELECT COUNT(*) FROM walk;
links (after the bad update)
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
|  1 | A    |      NULL |
|  2 | B    |         4 |
|  3 | C    |         2 |
|  4 | D    |         3 |
+----+------+-----------+
Show answer

It never finishes on its own: B's child is C, C's child is D, D's child is B again, forever. MySQL stops it at the recursion limit:

Result
ERROR 3636 (HY000): Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.

Carry the ids you've already visited and stop when you meet one again:

SQL
WITH RECURSIVE walk AS (
  SELECT id, name, CAST(id AS CHAR(500)) AS seen, 0 AS is_cycle
  FROM links WHERE id = 2
  UNION ALL
  SELECT l.id, l.name, CONCAT(w.seen, ',', l.id), FIND_IN_SET(l.id, w.seen) > 0
  FROM links l JOIN walk w ON l.parent_id = w.id
  WHERE w.is_cycle = 0
)
SELECT id, name, seen, is_cycle FROM walk;
Result
+------+------+---------+----------+
| id   | name | seen    | is_cycle |
+------+------+---------+----------+
|    2 | B    | 2       |        0 |
|    3 | C    | 2,3     |        0 |
|    4 | D    | 2,3,4   |        0 |
|    2 | B    | 2,3,4,2 |        1 |
+------+------+---------+----------+
What’s happening
  1. seen is a comma-separated list of the ids on the current path, cast wide in the anchor so it can grow.
  2. Each step checks whether the new id is already in the list with FIND_IN_SET(l.id, w.seen), which returns its position or 0.
  3. When the walk reaches B again, is_cycle becomes 1 and the row is still produced, so you can see where the loop closes (2,3,4,2).
  4. WHERE w.is_cycle = 0 stops the recursion from extending a row that has already looped, so the walk ends after four rows.
  5. Raising cte_max_recursion_depth would not help — a cycle is infinite. The real fix is in the data: a trigger or application check that refuses to make a node its own ancestor.

Alternative: UNION DISTINCT. Replacing UNION ALL with UNION DISTINCT (with only id, name in the CTE) also terminates, returning B, C and D once each: when the step produces (2, 'B') again, it's a duplicate of a row already in the result, so it's discarded and the recursion runs out of new rows. It's simpler, but it only works when the rows you carry don't change from step to step — add a depth column and every row is "new" again: with w.depth + 1 in the CTE, the UNION DISTINCT walk failed with the same error 3636.

Learn more: Recursive CTEs and Triggers.

Open in topic →

"How do you pivot rows into columns in MySQL?"

Show answer

"MySQL has no PIVOT operator, so I use conditional aggregation: group by the row key and write one SUM(CASE WHEN category = 'x' THEN amount ELSE 0 END) per output column. COUNT works the same way by summing a boolean, SUM(status = 'paid'), which is a MySQL shortcut because booleans are 0 and 1. If the columns aren't known in advance, I build the column list with GROUP_CONCAT from the distinct values and run it as a prepared statement — or, better, return the long format and pivot in the application. Unpivoting is UNION ALL of one SELECT per column, or a LATERAL derived table."

Open in topic →

Pivot revenue into one column per month

Turn the revenue above into one row per customer with feb, mar and apr columns and a total, showing 0 where a customer had no sales that month.

Show answer

One SUM(CASE …) per month column:

SQL
SELECT c.name AS customer,
  SUM(CASE WHEN o.ordered_at >= '2025-02-01' AND o.ordered_at < '2025-03-01'
           THEN oi.quantity * oi.unit_price ELSE 0 END) AS feb,
  SUM(CASE WHEN o.ordered_at >= '2025-03-01' AND o.ordered_at < '2025-04-01'
           THEN oi.quantity * oi.unit_price ELSE 0 END) AS mar,
  SUM(CASE WHEN o.ordered_at >= '2025-04-01' AND o.ordered_at < '2025-05-01'
           THEN oi.quantity * oi.unit_price ELSE 0 END) AS apr,
  SUM(oi.quantity * oi.unit_price) AS total
FROM customers c
JOIN orders o       ON o.customer_id = c.id AND o.status <> 'cancelled'
JOIN order_items oi ON oi.order_id = o.id
GROUP BY c.id, c.name
ORDER BY c.id;
Result
+----------+---------+--------+---------+---------+
| customer | feb     | mar    | apr     | total   |
+----------+---------+--------+---------+---------+
| Rohit    |  957.00 |  88.00 |    0.00 | 1045.00 |
| Maya     | 1048.00 |   0.00 |  116.00 | 1164.00 |
| Liam     |    0.00 | 127.00 |    0.00 |  127.00 |
| Sofia    |    0.00 | 249.00 |    0.00 |  249.00 |
| Noah     |    0.00 |   0.00 | 1016.00 | 1016.00 |
+----------+---------+--------+---------+---------+
What’s happening
  1. GROUP BY c.id, c.name makes one row per customer — the pivot's row key. All of a customer's order lines fall into that group.
  2. Each CASE passes a line's value through only if it belongs to that month, and 0 otherwise, so feb sums February lines and nothing else. Rohit's February: 899 + 2 × 29 = 957.
  3. ELSE 0 is why empty cells show 0.00. Leave the ELSE out and CASE returns NULL for non-matching lines; a bin that receives only NULLs sums to NULL.
  4. The date ranges are half-open (>= start AND < next start), which is correct for DATETIME values at any time of day and can use an index — MONTH(o.ordered_at) = 2 would also match February of every year.
  5. The columns are fixed in the SQL text: adding May means editing the query. That's the essence of a static pivot.

MySQL shortcuts: booleans are integers (TRUE is 1), and IF() is a two-branch CASE. This version shows both, and the difference NULL makes:

SQL
SELECT c.name AS customer,
  SUM((MONTH(o.ordered_at) = 2) * oi.quantity * oi.unit_price) AS feb,
  SUM(IF(MONTH(o.ordered_at) = 3, oi.quantity * oi.unit_price, NULL)) AS mar
FROM customers c
JOIN orders o       ON o.customer_id = c.id AND o.status <> 'cancelled'
JOIN order_items oi ON oi.order_id = o.id
GROUP BY c.id, c.name
ORDER BY c.id;
Result
+----------+---------+--------+
| customer | feb     | mar    |
+----------+---------+--------+
| Rohit    |  957.00 |  88.00 |
| Maya     | 1048.00 |   NULL |
| Liam     |    0.00 | 127.00 |
| Sofia    |    0.00 | 249.00 |
| Noah     |    0.00 |   NULL |
+----------+---------+--------+
What’s happening
  1. (MONTH(o.ordered_at) = 2) is 1 or 0, so multiplying by it keeps or zeroes each line. It's compact, but MySQL-specific and less readable than CASE.
  2. The mar column uses NULL as the "else". Maya and Noah had no March lines, so their bins only received NULLs and SUM returned NULL, not 0.
  3. Some reports want NULL ("no data") rather than 0 ("data, and it was zero") — choose deliberately, or wrap with COALESCE(…, 0).
  4. And there's no shortcut keyword: SELECT * FROM orders PIVOT (COUNT(id) FOR status IN ('paid','shipped')) AS p fails with ERROR 1064 (42000) near '(COUNT(id) FOR status IN ('paid','shipped')) AS p'.

Learn more: Conditional aggregation and pivots and CASE expressions.

Open in topic →

Order status counts per customer with a grand total — predict Zara's row

Predict the output, paying attention to Zara (no orders) and the total row.

SQL
SELECT COALESCE(c.name, 'All customers') AS customer,
  COUNT(o.id)                 AS orders,
  SUM(o.status = 'shipped')   AS shipped,
  SUM(o.status = 'paid')      AS paid,
  SUM(o.status = 'pending')   AS pending,
  SUM(o.status = 'cancelled') AS cancelled
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name WITH ROLLUP;
Show answer

Zara's order count is 0, but her status columns are NULL, not 0. WITH ROLLUP adds a final row whose name is NULL, which COALESCE relabels as "All customers".

Result
+---------------+--------+---------+------+---------+-----------+
| customer      | orders | shipped | paid | pending | cancelled |
+---------------+--------+---------+------+---------+-----------+
| Liam          |      2 |       1 |    0 |       0 |         1 |
| Maya          |      2 |       2 |    0 |       0 |         0 |
| Noah          |      1 |       0 |    1 |       0 |         0 |
| Rohit         |      2 |       1 |    1 |       0 |         0 |
| Sofia         |      1 |       0 |    0 |       1 |         0 |
| Zara          |      0 |    NULL | NULL |    NULL |      NULL |
| All customers |      8 |       4 |    2 |       1 |         1 |
+---------------+--------+---------+------+---------+-----------+
What’s happening
  1. The LEFT JOIN keeps Zara with one row where every o.* column is NULL.
  2. COUNT(o.id) skips NULLs, so her orders is 0. But o.status = 'shipped' is NULL = 'shipped', which is NULL, and SUM of only NULLs is NULL. Counts and sums disagree on empty groups.
  3. WITH ROLLUP appends a super-aggregate row over all groups, with the grouped column set to NULL. Its numbers are totals over all rows: 8 orders, 4 shipped, and so on.
  4. COALESCE(c.name, …) relabels that NULL. It's fragile: if a real customer had a NULL name, they'd be relabelled too. GROUPING(c.name) (MySQL 8.0+) returns 1 only on the rollup row, so IF(GROUPING(c.name), 'All customers', c.name) is the precise version.
  5. The row order isn't something to rely on: add ORDER BY (allowed with ROLLUP since 8.0.12), e.g. ORDER BY GROUPING(c.name), c.name, to put the total last explicitly.

With GROUPING() and COALESCE(SUM(…), 0) for the empty group:

SQL
SELECT IF(GROUPING(c.name), 'All customers', c.name) AS customer,
       COUNT(o.id) AS orders,
       COALESCE(SUM(o.status = 'shipped'), 0) AS shipped
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name WITH ROLLUP;
Result
+---------------+--------+---------+
| customer      | orders | shipped |
+---------------+--------+---------+
| Liam          |      2 |       1 |
| Maya          |      2 |       2 |
| Noah          |      1 |       0 |
| Rohit         |      2 |       1 |
| Sofia         |      1 |       0 |
| Zara          |      0 |       0 |
| All customers |      8 |       4 |
+---------------+--------+---------+
What’s happening
  1. GROUPING(c.name) is 1 on the rollup row and 0 elsewhere, so the label can't be confused with a real NULL name.
  2. COALESCE(SUM(…), 0) turns Zara's NULL into 0, which is what a status report should show.
  3. COUNT(…) never needs COALESCE: it always returns a number.

Learn more: WITH ROLLUP and Aggregate functions.

Open in topic →

Unpivot quarterly columns into rows

Turn this wide table into one row per region per quarter, and leave out quarters with no figure.

quarterly_sales
+--------+------+------+------+------+
| region | q1   | q2   | q3   | q4   |
+--------+------+------+------+------+
| North  |  120 |  135 | NULL |  160 |
| South  |   90 |   80 |  110 |   95 |
+--------+------+------+------+------+
Show answer

The portable answer is a UNION ALL of one SELECT per column:

SQL
SELECT region, 'q1' AS quarter, q1 AS sales FROM quarterly_sales
UNION ALL SELECT region, 'q2', q2 FROM quarterly_sales
UNION ALL SELECT region, 'q3', q3 FROM quarterly_sales
UNION ALL SELECT region, 'q4', q4 FROM quarterly_sales
ORDER BY region, quarter;
Result
+--------+---------+-------+
| region | quarter | sales |
+--------+---------+-------+
| North  | q1      |   120 |
| North  | q2      |   135 |
| North  | q3      |  NULL |
| North  | q4      |   160 |
| South  | q1      |    90 |
| South  | q2      |    80 |
| South  | q3      |   110 |
| South  | q4      |    95 |
+--------+---------+-------+
What’s happening
  1. Each SELECT turns one column into rows, tagging it with a literal quarter name. The first SELECT fixes the column names (quarter, sales) for the whole union.
  2. UNION ALL, not UNION: plain UNION removes duplicate rows, which would silently merge two regions that happen to have the same figure in the same quarter — and it costs a sort.
  3. The ORDER BY at the end applies to the whole union.
  4. North's missing Q3 comes out as a NULL row; the question asked to drop it, which needs a WHERE on each branch (or the next form).
  5. It reads the table four times. With many columns, that's slow and verbose.

Alternative: LATERAL (MySQL 8.0.14+) — read each row once and expand it:

SQL
SELECT s.region, u.quarter, u.sales
FROM quarterly_sales s,
LATERAL (SELECT 'q1' AS quarter, s.q1 AS sales
         UNION ALL SELECT 'q2', s.q2
         UNION ALL SELECT 'q3', s.q3
         UNION ALL SELECT 'q4', s.q4) AS u
WHERE u.sales IS NOT NULL
ORDER BY s.region, u.quarter;
Result
+--------+---------+-------+
| region | quarter | sales |
+--------+---------+-------+
| North  | q1      |   120 |
| North  | q2      |   135 |
| North  | q4      |   160 |
| South  | q1      |    90 |
| South  | q2      |    80 |
| South  | q3      |   110 |
| South  | q4      |    95 |
+--------+---------+-------+
What’s happening
  1. For each row s, the LATERAL derived table builds four rows from s's own columns — the table is scanned once.
  2. The comma before LATERAL is a cross join, which is fine because each derived table belongs to exactly one outer row.
  3. WHERE u.sales IS NOT NULL drops North's Q3, leaving seven rows.
  4. A wide table like this is usually a design smell: storing one row per (region, quarter) from the start makes every query simpler, which is the real lesson of unpivoting.

Learn more: Set operations: UNION, INTERSECT and EXCEPT and First, second and third normal form.

Open in topic →

A dynamic pivot: one column per order status, whatever statuses exist

Build a per-customer status table without hard-coding the status names in the query.

Show answer

Generate the column list from the data with GROUP_CONCAT, glue it into a SQL string, and run it as a prepared statement:

SQL
SET @cols = (
  SELECT GROUP_CONCAT(DISTINCT
           CONCAT('SUM(o.status = ''', status, ''') AS `', status, '`')
           ORDER BY status)
  FROM orders);
SELECT @cols;

SET @sql = CONCAT('SELECT c.name, ', @cols,
                  ' FROM customers c JOIN orders o ON o.customer_id = c.id',
                  ' GROUP BY c.id, c.name ORDER BY c.id');
PREPARE p FROM @sql;
EXECUTE p;
DEALLOCATE PREPARE p;
Result
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| @cols                                                                                                                                                     |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| SUM(o.status = 'pending') AS `pending`,SUM(o.status = 'paid') AS `paid`,SUM(o.status = 'shipped') AS `shipped`,SUM(o.status = 'cancelled') AS `cancelled` |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+

+-------+---------+------+---------+-----------+
| name  | pending | paid | shipped | cancelled |
+-------+---------+------+---------+-----------+
| Rohit |       0 |    1 |       1 |         0 |
| Maya  |       0 |    0 |       2 |         0 |
| Liam  |       0 |    0 |       1 |         1 |
| Sofia |       1 |    0 |       0 |         0 |
| Noah  |       0 |    1 |       0 |         0 |
+-------+---------+------+---------+-----------+
What’s happening
  1. The inner CONCAT writes one column expression per distinct status, like SUM(o.status = 'paid') AS `paid`. Inside a SQL string literal, '' is an escaped single quote.
  2. GROUP_CONCAT(DISTINCT … ORDER BY status) joins them with commas. The order is pending, paid, shipped, cancelled — not alphabetical — because status is an ENUM, and ENUMs sort by their definition order, not by their text.
  3. CONCAT builds the full query text in @sql; PREPARE parses it, EXECUTE runs it. Add a new status to the ENUM and use it, and the next run grows a column with no code change.
  4. Watch group_concat_max_len (default 1024 bytes): a longer column list is cut off with only a warning — with the limit set to 20, GROUP_CONCAT(name) returned Asha,Ben,Chloe,Dev,E and warning 1260 Row 5 was cut by GROUP_CONCAT() — so the generated SQL breaks. Raise it for the session when the list can be long.
  5. The values are pasted into SQL text, so this is only safe for values you control. Never build a dynamic pivot from user-supplied strings — that's SQL injection. Often the better design is to return the long format and pivot in the application or BI tool.

Learn more: GROUP_CONCAT and JSON aggregation and SQL injection and prepared statements.

Open in topic →

Each category's share of total revenue

Show revenue per top-level category (Electronics includes its subcategories) and each one's percentage of the total, ignoring cancelled orders.

Show answer

Electronics 91.6%, Books 8.4%. Aggregate first, then use an empty window to get the grand total on every row:

SQL
WITH cat_revenue AS (
  SELECT COALESCE(parent.name, c.name) AS top_category,
         SUM(oi.quantity * oi.unit_price) AS revenue
  FROM order_items oi
  JOIN orders o           ON o.id = oi.order_id AND o.status <> 'cancelled'
  JOIN products p         ON p.id = oi.product_id
  JOIN categories c       ON c.id = p.category_id
  LEFT JOIN categories parent ON parent.id = c.parent_id
  GROUP BY top_category
)
SELECT top_category, revenue,
       ROUND(100 * revenue / SUM(revenue) OVER (), 1) AS pct_of_total
FROM cat_revenue
ORDER BY revenue DESC;
Result
+--------------+---------+--------------+
| top_category | revenue | pct_of_total |
+--------------+---------+--------------+
| Electronics  | 3298.00 |         91.6 |
| Books        |  303.00 |          8.4 |
+--------------+---------+--------------+
What’s happening
  1. The LEFT JOIN to categories parent finds each category's parent. Laptops, Phones and Accessories have parent Electronics; Books has none, so parent.name is NULL.
  2. COALESCE(parent.name, c.name) rolls subcategories up into their parent and leaves top-level categories as themselves. This handles one level; a deeper tree needs the recursive CTE from the hierarchy questions.
  3. The CTE sums revenue per top-level category: Electronics 1798 + 799 + 701 = 3298, Books 303.
  4. SUM(revenue) OVER () — a window with no partition and no order — is the total of all rows, 3601, attached to each row. 100 × 3298 / 3601 = 91.6.
  5. The window is applied after the CTE's GROUP BY, so it sums two aggregated rows. You can even do it in one query: SUM(SUM(x)) OVER () is legal, because window functions run after grouping — run per leaf category, it gave the same percentages as the next query.

Alternative: a scalar subquery for the total (any version). Here per leaf category:

SQL
SELECT c.name AS category, SUM(oi.quantity * oi.unit_price) AS revenue,
       ROUND(100 * SUM(oi.quantity * oi.unit_price) /
             (SELECT SUM(quantity * unit_price)
              FROM order_items oi2 JOIN orders o2 ON o2.id = oi2.order_id
              WHERE o2.status <> 'cancelled'), 1) AS pct
FROM order_items oi
JOIN orders o     ON o.id = oi.order_id AND o.status <> 'cancelled'
JOIN products p   ON p.id = oi.product_id
JOIN categories c ON c.id = p.category_id
GROUP BY c.id, c.name
ORDER BY revenue DESC;
Result
+-------------+---------+------+
| category    | revenue | pct  |
+-------------+---------+------+
| Laptops     | 1798.00 | 49.9 |
| Phones      |  799.00 | 22.2 |
| Accessories |  701.00 | 19.5 |
| Books       |  303.00 |  8.4 |
+-------------+---------+------+
What’s happening
  1. The subquery is uncorrelated, so it runs once and returns 3601.
  2. The trap is keeping the two filters identical: if the subquery forgot status <> 'cancelled', the total would include the cancelled MacBook (1,299) and every percentage would be too small. The window version can't drift, because it sums the same rows the report shows.
  3. The rounded percentages add up to 100.0 here, but in general rounded shares don't always sum to exactly 100 — say so if a report shows a total line.

Learn more: Window functions: OVER and PARTITION BY.

Open in topic →

A department report that includes the empty department

For each department show headcount, minimum, maximum and average salary and total payroll. Research has nobody and must still appear, with headcount 0 and payroll 0.

Show answer

Start from departments and LEFT JOIN employees, so empty departments survive:

SQL
SELECT d.name AS department,
       COUNT(e.id)                AS headcount,
       MIN(e.salary)              AS min_salary,
       MAX(e.salary)              AS max_salary,
       ROUND(AVG(e.salary), 0)    AS avg_salary,
       COALESCE(SUM(e.salary), 0) AS payroll
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name
ORDER BY d.id;
Result
+-------------+-----------+------------+------------+------------+-----------+
| department  | headcount | min_salary | max_salary | avg_salary | payroll   |
+-------------+-----------+------------+------------+------------+-----------+
| Engineering |         4 |  118000.00 |  185000.00 |     146750 | 587000.00 |
| Sales       |         3 |   95000.00 |  130000.00 |     108000 | 324000.00 |
| Support     |         2 |   72000.00 |   88000.00 |      80000 | 160000.00 |
| Research    |         0 |       NULL |       NULL |       NULL |      0.00 |
+-------------+-----------+------------+------------+------------+-----------+
What’s happening
  1. departments is on the left, so all four departments produce at least one row. Research's row has e.* all NULL.
  2. COUNT(e.id) counts non-NULL ids: 0 for Research. COUNT(*) would say 1, counting the padding row — see Tricky NULL and JOIN puzzles.
  3. MIN, MAX and AVG of no values are NULL, which is honest: there is no minimum salary in an empty department. Only payroll is wrapped in COALESCE, because "total spent" really is 0.
  4. Jonas (no department) is not in any row. Starting from employees instead would include him in a NULL department but drop Research — the direction of the join decides which "orphans" you see.

Learn more: LEFT and RIGHT OUTER JOIN and COUNT(*) vs COUNT(column) vs COUNT(DISTINCT).

Open in topic →

"Why can NOT IN return no rows?"

Show answer

"If the subquery returns even one NULL, x NOT IN (…) can never be true: it becomes x <> a AND x <> b AND x <> NULL, and the last comparison is unknown, so the whole condition is unknown and every row is filtered out. IN doesn't have the problem, because one true match is enough. The fix is NOT EXISTS, which only asks whether a matching row exists and isn't affected by NULLs, or a LEFT JOIN … WHERE right.id IS NULL, or filtering NULLs out of the subquery. I default to NOT EXISTS for anti-joins."

Open in topic →

Which employees manage nobody? (NOT IN and NULL)

Predict the result. manager_id is NULL for Asha, the CEO.

SQL
SELECT name FROM employees
WHERE id NOT IN (SELECT manager_id FROM employees);
Show answer

No rows at all — even though six employees manage nobody:

Result
Empty set

Use NOT EXISTS, which isn't affected by the NULL:

SQL
SELECT e.name
FROM employees e
WHERE NOT EXISTS (SELECT 1 FROM employees r WHERE r.manager_id = e.id);
Result
+-------+
| name  |
+-------+
| Chloe |
| Dev   |
| Farid |
| Grace |
| Isla  |
| Jonas |
+-------+
What’s happening
  1. The subquery SELECT manager_id FROM employees returns NULL, 1, 1, 2, 1, 5, 5, 1, 8, 1 — the NULL is Asha's.
  2. For Chloe (id 3): 3 NOT IN (NULL, 1, 2, 5, 8, …) means 3 <> NULL AND 3 <> 1 AND …. The first comparison is unknown, every other one is true, so the whole condition is unknown and Chloe is dropped. The same happens to every row.
  3. NOT EXISTS asks a different question: "is there a row r whose manager_id equals my id?". For Chloe there isn't, so NOT EXISTS is true. Asha's NULL simply never matches anyone and causes no harm.
  4. Ben, Elena, Hiro and Asha are correctly excluded: someone reports to each of them.
  5. Two other correct fixes: add WHERE manager_id IS NOT NULL inside the NOT IN subquery (it returned the same six names), or the anti-join LEFT JOIN employees r ON r.manager_id = e.id WHERE r.id IS NULL (same six again).

Contrast: when NOT IN is safe. "Customers who never ordered" (LeetCode's Customers Who Never Order) works with NOT IN, because orders.customer_id is NOT NULL:

SQL
SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
Result
+------+
| name |
+------+
| Zara |
+------+
What’s happening
  1. The subquery returns 1, 1, 2, 3, 3, 4, 5, 2, with no NULL, so every <> comparison is a real true or false.
  2. Zara (id 6) differs from all of them, so she's returned. The LEFT JOIN … IS NULL and NOT EXISTS versions also returned only Zara.
  3. It's safe today. If someone later makes customer_id nullable (guest checkout), this query silently starts returning nothing. NOT EXISTS doesn't depend on the schema staying that way, which is why it's the better default.

Learn more: NULL and three-valued logic and IN vs EXISTS.

Open in topic →

Predict: how many customers are not in Toronto?

Six customers: two in Toronto, one each in Mumbai, London and Dubai, and Sofia, whose city is NULL. Predict the count.

SQL
SELECT COUNT(*) AS not_toronto FROM customers WHERE city <> 'Toronto';
Show answer

3, not 4. Sofia's NULL city makes city <> 'Toronto' unknown, so she isn't counted.

Result
+-------------+
| not_toronto |
+-------------+
|           3 |
+-------------+
What’s happening
  1. Rohit and Noah (Toronto) give false. Maya, Liam and Zara give true.
  2. Sofia: NULL <> 'Toronto' is unknown. WHERE keeps only true rows, so she's dropped. Her row is in neither city = 'Toronto' nor city <> 'Toronto' — the two conditions don't cover the table between them.
  3. If "not Toronto" should include unknown cities, say so explicitly: WHERE city <> 'Toronto' OR city IS NULL returned 4, and WHERE NOT (city <=> 'Toronto') also returned 4.
  4. A related check: SELECT COUNT(*), COUNT(city) FROM customers returns 6 and 5 — COUNT(column) skips NULLs, which is another way the missing city disappears from reports.

Learn more: NULL and three-valued logic.

Open in topic →

Predict: employees per department, COUNT(*) vs COUNT(e.id)

Predict both columns for Research, which has no employees.

SQL
SELECT d.name, COUNT(*) AS count_star, COUNT(e.id) AS count_id
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name
ORDER BY d.id;
Show answer

Research gets count_star = 1 and count_id = 0.

Result
+-------------+------------+----------+
| name        | count_star | count_id |
+-------------+------------+----------+
| Engineering |          4 |        4 |
| Sales       |          3 |        3 |
| Support     |          2 |        2 |
| Research    |          1 |        0 |
+-------------+------------+----------+
What’s happening
  1. The LEFT JOIN gives Research one row, with every e.* column NULL, so that the department isn't lost.
  2. COUNT(*) counts rows in the group. Research's group has one row (the padding row), so it says 1 — a department with one phantom employee.
  3. COUNT(e.id) counts non-NULL values of e.id. The padding row's e.id is NULL, so it says 0.
  4. Rule: after an outer join, count a column from the optional side, preferably its primary key (never NULL for a real row). The same rule fixed the calendar report in Gaps and islands.

Learn more: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT).

Open in topic →

Spot the bug: the LEFT JOIN that drops customers

The goal: list every customer with their number of shipped orders, including customers with none. This returns only three customers. Why?

SQL
SELECT c.name, COUNT(o.id) AS shipped_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'shipped'
GROUP BY c.id, c.name
ORDER BY c.id;
Show answer

The WHERE runs after the join and filters out the NULL-padded rows, which turns the LEFT JOIN back into an inner join:

Result
+-------+----------------+
| name  | shipped_orders |
+-------+----------------+
| Rohit |              1 |
| Maya  |              2 |
| Liam  |              1 |
+-------+----------------+

Move the condition into the ON clause, so it decides which orders match, not which rows survive:

SQL
SELECT c.name, COUNT(o.id) AS shipped_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'shipped'
GROUP BY c.id, c.name
ORDER BY c.id;
Result
+-------+----------------+
| name  | shipped_orders |
+-------+----------------+
| Rohit |              1 |
| Maya  |              2 |
| Liam  |              1 |
| Sofia |              0 |
| Noah  |              0 |
| Zara  |              0 |
+-------+----------------+
What’s happening
  1. In the buggy query, the join first produces every customer–order pair plus a padding row for Zara. Sofia's only order is pending and Noah's is paid.
  2. WHERE o.status = 'shipped' then removes Sofia's and Noah's rows (wrong status) and Zara's padding row (NULL = 'shipped' is unknown). Their groups disappear entirely.
  3. In the fixed query the status test is part of the match. Sofia's pending order doesn't match, so the LEFT JOIN gives her a padding row instead — and COUNT(o.id) counts it as 0.
  4. The rule for outer joins: conditions on the optional (right-hand) table go in ON; conditions on the preserved table go in WHERE. For an inner join it makes no difference where you put them.
  5. SUM(o.status = 'shipped') with no filter at all also works, but returned NULL for Zara rather than 0, for the reason shown in Pivoting and reporting.

Learn more: Join conditions: ON vs WHERE vs USING.

Open in topic →

Spot the bug: deposits and withdrawals that are three times too big

Ava deposited 100 and 50 and withdrew 30, 20 and 10. Raj deposited 70. Why does this report say Ava deposited 450?

SQL
SELECT a.owner, SUM(d.amount) AS deposited, SUM(w.amount) AS withdrawn
FROM accounts a
LEFT JOIN deposits d    ON d.account_id = a.id
LEFT JOIN withdrawals w ON w.account_id = a.id
GROUP BY a.id, a.owner
ORDER BY a.id;
Show answer

Joining one account to two independent child tables pairs every deposit with every withdrawal — a fan-out:

Result
+-------+-----------+-----------+
| owner | deposited | withdrawn |
+-------+-----------+-----------+
| Ava   |       450 |       120 |
| Raj   |        70 |      NULL |
+-------+-----------+-----------+

Aggregate each child table before joining, so each join is one-to-one:

SQL
SELECT a.owner,
       COALESCE(d.total, 0) AS deposited,
       COALESCE(w.total, 0) AS withdrawn
FROM accounts a
LEFT JOIN (SELECT account_id, SUM(amount) AS total
           FROM deposits GROUP BY account_id) d    ON d.account_id = a.id
LEFT JOIN (SELECT account_id, SUM(amount) AS total
           FROM withdrawals GROUP BY account_id) w ON w.account_id = a.id
ORDER BY a.id;
Result
+-------+-----------+-----------+
| owner | deposited | withdrawn |
+-------+-----------+-----------+
| Ava   |       150 |        60 |
| Raj   |        70 |         0 |
+-------+-----------+-----------+
What’s happening
  1. Ava has 2 deposits and 3 withdrawals. The joins produce 2 × 3 = 6 rows for her: each deposit appears 3 times and each withdrawal twice.
  2. So SUM(d.amount) is (100 + 50) × 3 = 450 and SUM(w.amount) is (30 + 20 + 10) × 2 = 120. Raj has one deposit and no withdrawals, so his single row is correct by luck.
  3. The fix pre-aggregates each child table in a derived table: one row per account, 150 and 60 for Ava. Joining one-row-per-account tables can't multiply anything.
  4. COALESCE(…, 0) turns Raj's missing withdrawals into 0 for the report.
  5. SUM(DISTINCT d.amount) is not a fix: it would merge two genuinely separate deposits of the same amount. A correlated subquery per column ((SELECT COALESCE(SUM(amount), 0) FROM deposits d WHERE d.account_id = a.id)) also gave 150 / 60 and 70 / 0.

The milder version of the same bug is counting orders after joining order lines: COUNT(o.id) over customers JOIN orders JOIN order_items returned 4 orders for Rohit (he has 2 orders with 2 lines each). COUNT(DISTINCT o.id) returned the correct 2 — DISTINCT is a valid fix for counting keys, just not for summing amounts.

Learn more: Joining more than two tables and Derived tables.

Open in topic →

Predict the row counts of every join type

Predict the number of rows each join returns.

ta.k: 1, 1, 2, NULL tb.k: 1, 1, 1, 3, NULL
SQL
SELECT
 (SELECT COUNT(*) FROM ta JOIN tb ON ta.k = tb.k)        AS inner_rows,
 (SELECT COUNT(*) FROM ta LEFT JOIN tb ON ta.k = tb.k)   AS left_rows,
 (SELECT COUNT(*) FROM ta RIGHT JOIN tb ON ta.k = tb.k)  AS right_rows,
 (SELECT COUNT(*) FROM ta CROSS JOIN tb)                 AS cross_rows,
 (SELECT COUNT(*) FROM ta JOIN tb ON ta.k <=> tb.k)      AS null_safe_rows;
Show answer

Inner 6, left 8, right 8, cross 20, null-safe 7 — and a full outer join (emulated, since MySQL has no FULL JOIN) would return 10.

Result
+------------+-----------+------------+------------+----------------+
| inner_rows | left_rows | right_rows | cross_rows | null_safe_rows |
+------------+-----------+------------+------------+----------------+
|          6 |         8 |          8 |         20 |              7 |
+------------+-----------+------------+------------+----------------+
What’s happening
  1. Inner: only key 1 exists on both sides. Two 1s on the left × three 1s on the right = 6 handshakes. Key 2, key 3 and both NULLs match nothing (NULL = NULL is unknown).
  2. Left: the 6 matches, plus one padding row for each unmatched left row — key 2 and NULL — = 8.
  3. Right: the 6 matches, plus padding for tb's unmatched 3 and NULL = 8.
  4. Cross: every pair, 4 × 5 = 20. No condition at all.
  5. Null-safe join with <=>: the 6 key-1 pairs plus the two NULLs now matching each other = 7.
  6. Full outer = matches + unmatched left + unmatched right = 6 + 2 + 2 = 10. In MySQL you write it as the LEFT JOIN UNION ALL the RIGHT JOIN rows whose left side is NULL, which returned 10 — see FULL OUTER JOIN in MySQL.

NULL is treated differently by grouping and set operations. GROUP BY and UNION treat all NULLs as one value, unlike =:

SQL
SELECT k, COUNT(*) FROM ta GROUP BY k;
SELECT k FROM ta UNION SELECT k FROM tb;
SELECT COUNT(DISTINCT k) FROM ta;
Result
+------+----------+
| k    | COUNT(*) |
+------+----------+
|    1 |        2 |
|    2 |        1 |
| NULL |        1 |
+------+----------+

+------+
| k    |
+------+
|    1 |
|    2 |
| NULL |
|    3 |
+------+

+-------------------+
| COUNT(DISTINCT k) |
+-------------------+
|                 2 |
+-------------------+
What’s happening
  1. GROUP BY k puts the NULL in its own group — all NULLs together, as if they were equal.
  2. UNION removes duplicates the same way: the two tables' NULLs collapse into one NULL row. (UNION ALL would keep both.)
  3. COUNT(DISTINCT k) ignores NULL entirely: 2 distinct non-NULL values. So "how many distinct values?" has two different answers — 3 groups, 2 distinct values.
  4. The standard calls this "not distinct" (grouping) versus "not equal" (comparison), and it's exactly the difference between <=> and = in MySQL.

Learn more: INNER JOIN, CROSS JOIN and DISTINCT.

Open in topic →

Employees with a bonus under 1,000 — including those with no bonus

Report every employee whose bonus is under 1,000, counting "no bonus" as 0. Then predict the three averages.

bonuses (employee_id, bonus)
2 Ben 5000 · 3 Chloe 800 · 5 Elena 1200 · 8 Hiro NULL   — nobody else has a row
SQL
SELECT AVG(bonus) AS avg_ignoring_null,
       AVG(COALESCE(bonus, 0)) AS avg_null_as_zero,
       COUNT(bonus) AS counted
FROM bonuses;
Show answer

The obvious LEFT JOIN … WHERE b.bonus < 1000 returns only Chloe: everyone without a bonus row has b.bonus = NULL, and NULL < 1000 is unknown. Include the NULLs explicitly:

SQL
SELECT e.name, b.bonus
FROM employees e
LEFT JOIN bonuses b ON b.employee_id = e.id
WHERE b.bonus < 1000 OR b.bonus IS NULL
ORDER BY e.id;
Result
+-------+-------+
| name  | bonus |
+-------+-------+
| Asha  |  NULL |
| Chloe |   800 |
| Dev   |  NULL |
| Farid |  NULL |
| Grace |  NULL |
| Hiro  |  NULL |
| Isla  |  NULL |
| Jonas |  NULL |
+-------+-------+
What’s happening
  1. The LEFT JOIN keeps all ten employees. Six have no bonus row; Hiro has a row whose bonus is NULL. In the joined result both look identical: b.bonus is NULL.
  2. b.bonus < 1000 is true for Chloe, false for Ben and Elena, and unknown for the seven NULLs.
  3. OR b.bonus IS NULL turns those seven unknowns into true, giving eight rows. WHERE COALESCE(b.bonus, 0) < 1000 returned the same eight.
  4. If you needed to tell "no bonus row" from "a row with an unknown bonus", test b.employee_id IS NULL — the join key is NULL only on padding rows.
  5. This is LeetCode's Employee Bonus, and the IS NULL branch is the whole point of it.

The averages differ because aggregates skip NULLs:

Result
+-------------------+------------------+---------+
| avg_ignoring_null | avg_null_as_zero | counted |
+-------------------+------------------+---------+
|         2333.3333 |        1750.0000 |       3 |
+-------------------+------------------+---------+
What’s happening
  1. AVG(bonus) averages only the three known bonuses: (5000 + 800 + 1200) / 3 = 2333.33. Hiro's NULL is left out of both the sum and the count.
  2. AVG(COALESCE(bonus, 0)) treats Hiro's bonus as 0: 7000 / 4 = 1750. SUM(bonus) / COUNT(*) also gives 1750.
  3. COUNT(bonus) is 3: the denominator AVG really used.
  4. Neither average is "right"; they answer different questions ("average of known bonuses" vs "average per row"). The interview point is knowing that AVG silently changes its denominator when NULLs appear.

Learn more: Aggregate functions and NULL and three-valued logic.

Open in topic →

What is MongoDB, and how is it different from MySQL?

Show answer

MongoDB is a document database: it stores data as BSON documents (binary JSON) grouped into collections, and a document can nest objects and arrays, so related data that is read together can live in one document instead of being normalised across tables and joined. Collections don't enforce a fixed schema by default, though you can add JSON Schema validation. It has a rich query language, secondary indexes, an aggregation pipeline for analytics and joins ($lookup), multi-document ACID transactions since 4.0, replica sets for high availability and built-in sharding for horizontal scale. MySQL is relational: fixed schemas, normalised tables, joins and SQL, with foreign keys enforced by the database. I'd pick MongoDB when the data is naturally hierarchical or varies in shape and the access pattern is "load this aggregate", and a relational database when the data is highly relational, I need ad-hoc SQL reporting, or many operations must keep invariants across entities.

Open in topic →

What is BSON and why doesn't MongoDB just store JSON?

Show answer

BSON is the binary encoding MongoDB uses for documents on disk and on the wire. Compared with JSON text it adds types JSON lacks — 32- and 64-bit integers, doubles, Decimal128, dates, ObjectId, binary data, regular expressions — and it prefixes documents and strings with their lengths, so the server can traverse and skip fields quickly without parsing everything. The cost is that it can be slightly bigger than the equivalent JSON, because of the type tags and lengths. A document can be at most 16 MiB of BSON.

Open in topic →

How is an ObjectId generated, and can I rely on it for ordering?

Show answer

An ObjectId is 12 bytes: a 4-byte timestamp in seconds, a 5-byte random value generated once per client process, and a 3-byte counter starting from a random value. The driver generates it client-side, so ids are unique across machines without coordination. Because the timestamp comes first, ObjectIds sort roughly by creation time and getTimestamp() gives the creation second, but the order isn't strict — ids from the same second, or from machines with different clocks, can be out of order. If I need exact ordering or sub-second precision I store and index a date field.

Open in topic →

What does this session print?

mongosh
use shop_tmp
db.getName()
db.getCollectionNames()
Show answer

switched to db shop_tmp, then shop_tmp, then [].

What’s happening
  1. use shop_tmp only changes which database the shell's db variable points at. It succeeds even though shop_tmp doesn't exist, and prints switched to db shop_tmp.
  2. db.getName() reports the new current database, shop_tmp.
  3. getCollectionNames() returns an empty array: nothing has been written, so the database has no collections and won't appear in show dbs until the first insert.
Open in topic →

How do you do a JOIN in MongoDB?

Show answer

Usually you design so you don't need one: data that is read together is embedded in one document, so one query returns it. When you do need to combine collections — references to shared data, many-to-many relationships, reporting — you use the $lookup stage in an aggregation pipeline, which performs a left outer join and puts the matching documents into an array field; $unwind can flatten that array if you want one result per match. There are no foreign-key constraints, so the application keeps references consistent. For hot paths I'd make sure the foreign field is indexed, and I'd avoid designs that need many lookups per request.

Open in topic →

Self-managed MongoDB or Atlas?

Show answer

Atlas is MongoDB's managed service: it handles provisioning, replica sets, backups with point-in-time restore, monitoring, scaling and upgrades, on AWS, Azure or Google Cloud, and adds Atlas-only features like Atlas Search and Vector Search. Self-managed (Community or Enterprise) gives full control over hardware, versions and network, and can be cheaper at scale or required for on-premises or regulatory reasons, but you own operations: replica-set setup, backups, upgrades, security hardening. For most teams without a dedicated database operations group, Atlas is the default; I'd go self-managed when there's a hard requirement for it.

Open in topic →

What's the difference between insertOne, insertMany and bulkWrite?

Show answer

insertOne inserts one document and returns its insertedId. insertMany sends an array in one round trip and returns the ids by array position; it's ordered by default, so it stops at the first error, and with ordered: false it continues and reports all errors at the end — in neither case are the successful inserts rolled back. bulkWrite mixes inserts, updates, replaces and deletes in one batch with the same ordered/unordered choice. None of them is a transaction; for all-or-nothing I'd use a multi-document transaction. The legacy insert() still runs in mongosh with a deprecation warning, but it's not something to write today.

Open in topic →

What's the difference between find and findOne?

Show answer

find returns a cursor over all matching documents; the driver fetches them in batches as you iterate, and you can chain sort, skip, limit and projection on it. findOne returns the first matching document itself, or null if nothing matches — internally it's a find with limit 1. Both accept the same filter and projection arguments, so to get only some fields from findOne you pass the projection as the second argument; you can't chain cursor methods on it. Without a sort, "first" just means whatever the query plan returns first, so if I care which document I get, I sort explicitly.

Open in topic →

Predict the result: the same key twice

mongosh
db.users.find({ age: { $gt: 30 }, age: { $lt: 40 } }, { _id: 0, name: 1, age: 1 })
Show answer

It returns Alice (28), Dana (35) and Farid (19) — everyone under 40 — not "between 30 and 40".

mongosh
db.users.find({ age: { $gt: 30 }, age: { $lt: 40 } }, { _id: 0, name: 1, age: 1 })
Result
[
  { name: 'Alice', age: 28 },
  { name: 'Dana', age: 35 },
  { name: 'Farid', age: 19 }
]
What’s happening
  1. The filter is a JavaScript object literal, and an object can't have two age keys. JavaScript keeps the last one, so the object the shell sends is just { age: { $lt: 40 } }.
  2. MongoDB never sees $gt: 30 at all, and no error is raised anywhere.
  3. age < 40 matches Alice, Dana and Farid (Grace's string age is skipped).
  4. The fix is to put both operators in one object, { age: { $gt: 30, $lt: 40 } } (Dana only), or to use $and with two separate filters.
Open in topic →

Spot the bug: a 5-star review with a comment

mongosh
// Intention: products where ONE review is 5 stars AND has a comment
db.products.find({ "reviews.rating": 5, "reviews.comment": { $exists: true } }, { _id: 0, name: 1 })
Show answer

It also returns Designing Data-Intensive Applications, whose 5-star review has no comment.

mongosh
db.products.find({ "reviews.rating": 5, "reviews.comment": { $exists: true } }, { _id: 0, name: 1 })
db.products.find({ reviews: { $elemMatch: { rating: 5, comment: { $exists: true } } } }, { _id: 0, name: 1 })
Result
[
  { name: 'ThinkBook 14' },
  { name: 'MacBook Air' },
  { name: 'SQL Performance Explained' },
  { name: 'Designing Data-Intensive Applications' }
]
[
  { name: 'ThinkBook 14' },
  { name: 'MacBook Air' },
  { name: 'SQL Performance Explained' }
]
What’s happening
  1. The two dot-notation conditions are tested independently: "some review is rated 5" and "some review has a comment".
  2. The ThinkBook, the MacBook and the SQL book each have a 5-star review with a comment, so they are correct matches.
  3. Designing Data-Intensive Applications slips in because Alice's review is the 5-star one (no comment) and Dana's 4-star review is the one with a comment. Each condition is met, by a different review.
  4. $elemMatch applies both conditions to the same review, and the book drops out: three products instead of four.
Open in topic →

How do you query a field inside an embedded document or an array of documents?

Show answer

With dot notation in quotes — { "address.city": "Toronto" } — which also traverses arrays, so { "reviews.rating": 5 } matches if any review has rating 5, and a numeric segment like "reviews.0.rating" targets a position. Matching the embedded document itself, { address: { city: "Toronto" } }, is exact equality including field order, so it's rarely what you want. When several conditions must hold for the same array element I use $elemMatch, because separate dot-notation conditions can each be satisfied by different elements.

Open in topic →

What's the difference between { field: null } and { field: { $exists: false } }?

Show answer

{ field: null } matches documents where the field is null and documents where the field is missing entirely. { field: { $exists: false } } matches only documents that don't have the field. To match only an explicit null I use { field: { $type: "null" } }. And $exists: true matches any document with the key, even if the value is null. The distinction matters for data cleaning and for sparse or partial indexes, which treat missing fields differently from null ones.

Open in topic →

Predict the order

mongosh
db.mixed.insertMany([{ _id: 1, v: "10" }, { _id: 2, v: 9 }, { _id: 3, v: null }, { _id: 4 }, { _id: 5, v: 100 }])
db.mixed.find({}, { _id: 1 }).sort({ v: 1, _id: 1 })
Show answer

_id order: 3, 4, 2, 5, 1.

mongosh
db.mixed.insertMany([{ _id: 1, v: "10" }, { _id: 2, v: 9 }, { _id: 3, v: null }, { _id: 4 }, { _id: 5, v: 100 }]).insertedIds
db.mixed.find({}, { _id: 1 }).sort({ v: 1, _id: 1 })
Result
{ '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
[ { _id: 3 }, { _id: 4 }, { _id: 2 }, { _id: 5 }, { _id: 1 } ]
What’s happening
  1. Type order comes first: null and missing are lowest, so _id: 3 (null) and _id: 4 (missing) lead. They tie on v, and the _id: 1 tiebreaker puts 3 before 4.
  2. Numbers come next, sorted numerically: 9 (_id: 2) then 100 (_id: 5).
  3. Strings come after every number, so "10" (_id: 1) is last — even though it "looks" smaller than 100.
  4. Lesson: if a field's type is inconsistent, sorting on it gives results that look wrong. Fix the types ($exists and $type).
Open in topic →

How do you paginate in MongoDB, and what's wrong with skip?

Show answer

The simple way is sort plus skip((page - 1) * size) plus limit(size), always with a deterministic sort that ends in a unique field. The problem is that skip still scans and discards every skipped entry, so cost grows linearly with page depth, and concurrent inserts make items shift between pages. For large or infinite-scroll lists I use keyset (range) pagination: sort on an indexed unique key, remember the last value of the previous page, and query { key: { $gt: last } } with limit — constant cost per page. The trade-off is that you can't jump to an arbitrary page number.

Open in topic →

countDocuments vs estimatedDocumentCount?

Show answer

countDocuments(filter) executes an aggregation that matches and counts, so it's exact and supports any query filter, but its cost is proportional to the number of matching documents or index entries. estimatedDocumentCount() takes no filter and returns the count from collection metadata, so it's constant-time but can be off after an unclean shutdown or include orphaned documents on sharded clusters. The old count() is deprecated. I use the estimate for UI totals on big collections and countDocuments whenever correctness matters or there's a filter.

Open in topic →

deleteMany({}) vs drop()?

Show answer

deleteMany({}) removes every document individually but keeps the collection, its indexes and its options such as validation rules; each delete is a write that goes through the oplog, so on a large collection it's slow and generates a lot of replication traffic. drop() removes the collection with its indexes and metadata in one quick operation. To empty a large collection completely I'd drop and recreate it (with its indexes and validator); to remove a subset I'd use deleteMany with a filter, after checking it with countDocuments.

Open in topic →

What does an update return, and what's the difference between matchedCount and modifiedCount?

Show answer

updateOne and updateMany return acknowledged, matchedCount, modifiedCount, upsertedCount and upsertedId. matchedCount is how many documents the filter selected; modifiedCount is how many were actually changed. They differ when the update is a no-op — for example $set-ing a field to the value it already has — because MongoDB skips writing unchanged documents. So matchedCount: 0 means "nothing found", and matchedCount: 1, modifiedCount: 0 means "found, already in that state". updateOne changes at most one document; updateMany changes every match, each document atomically but not the batch as a whole.

Open in topic →

Predict the result: two clients, one counter

mongosh
// Client A and client B both run this at the same moment on { _id: "home", views: 10 }:
db.pages.updateOne({ _id: "home" }, { $inc: { views: 1 } })
Show answer

views ends at 12.

What’s happening
  1. Each updateOne is applied by the server as one atomic operation on the document: read the current value, add 1, write — with the document locked against other writers in between.
  2. Whichever update goes first takes views from 10 to 11; the second then sees 11 and takes it to 12.
  3. Compare the read-modify-write version in application code: both clients findOne and see 10, both compute 11, both $set: { views: 11 } — one increment is lost. That "lost update" is exactly what $inc prevents.
Open in topic →
InterviewCh 18 Upserts

What is an upsert and when would you use it?

Show answer

An upsert is an update with upsert: true: if the filter matches a document it's updated; if nothing matches, a new document is inserted, built from the filter's equality fields plus the update operators. The result tells you which happened — upsertedId and upsertedCount: 1 for an insert, matchedCount: 1 for an update. I use it for idempotent "create or update" writes: syncing records from another system, counters keyed by date, user settings. $setOnInsert sets fields only when inserting, like createdAt. To make it safe under concurrency there should be a unique index on the key in the filter.

Open in topic →

When would you use findOneAndUpdate instead of updateOne?

Show answer

When I need the document itself as part of the same atomic operation: claiming a job from a queue (set status: "running" and get the job), generating a sequence number with $inc and upsert, or decrementing stock and returning the remaining quantity. updateOne only returns counts, so getting the document would need a second read, which another client could change in between. By default findOneAndUpdate returns the pre-update document; returnDocument: "after" returns the new one. It modifies at most one document, and the sort option controls which.

Open in topic →

Predict the result: $push an array

mongosh
// tags is ["vip"]
db.users.updateOne({ _id: 1 }, { $push: { tags: ["a", "b"] } })
Show answer

tags becomes ["vip", ["a", "b"]] — one new element that is itself an array.

mongosh
db.users.updateOne({ _id: 2 }, { $set: { tags: ["vip"] } })
db.users.updateOne({ _id: 2 }, { $push: { tags: ["a", "b"] } })
db.users.findOne({ _id: 2 }).tags
Result
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
[ 'vip', [ 'a', 'b' ] ]
What’s happening
  1. Bob's tags is set to ["vip"] first so the example starts where the question does.
  2. $push appends its value as one element, and the value here is an array, so the array is nested inside tags.
  3. To append "a" and "b" as two separate elements, use $push: { tags: { $each: ["a", "b"] } } — the same $each modifier $addToSet uses.
Open in topic →

$push vs $addToSet?

Show answer

Both append to an array atomically. $push always appends, allowing duplicates, and supports the $each, $position, $sort and $slice modifiers, so it can maintain sorted or capped arrays. $addToSet appends only if an equal value isn't already present, giving set semantics — it compares whole values, so embedded documents must match exactly, field order included. Both need $each to add several values as separate elements. For removal there's $pull (by value or condition), $pullAll (a list of values) and $pop (first or last). I'd also keep arrays bounded, for example with $push plus $slice, so documents don't grow toward the 16 MB limit.

Open in topic →

Which operator?

mongosh
// For every order, mark the line items whose qty is 0 as "removed".
db.orders.updateMany({}, { $set: { "items.???.status": "removed" } }, /* options? */)
Show answer

$[z] with arrayFilters: [{ "z.qty": 0 }].

What’s happening
  1. $ would mark only the first zero-quantity item in each order, and it needs the filter to mention items — not enough when an order can have several.
  2. $[] would mark every item as removed, including ones with quantity.
  3. "items.$[z].status" with { arrayFilters: [ { "z.qty": 0 } ] } marks exactly the zero-quantity items, in every order, in one updateMany.
Open in topic →

Explain $, $[] and $[<identifier>] with arrayFilters.

Show answer

All three update elements of an array without knowing their indexes. The positional $ updates the first element that the query filter matched, so the filter must include a condition on the array. $[] updates every element of the array in each matched document — if one element matched the filter, all of them are still updated. $[<identifier>] updates every element that satisfies the corresponding condition in the arrayFilters option, so it targets exactly the matching elements, possibly several per document, and identifiers can be nested for arrays of arrays. $[] and arrayFilters were added in MongoDB 3.6.

Open in topic →

What is an update with an aggregation pipeline, and when do you need one?

Show answer

Since MongoDB 4.2 the update argument of updateOne, updateMany and findOneAndUpdate can be an array of pipeline stages — $set/$addFields, $unset, $project, $replaceRoot, $replaceWith — instead of operator documents. That lets the new value be computed from the document's existing fields with aggregation expressions: concatenating fields, converting types with $toInt or $toDate, conditional values with $cond, transforming arrays with $map and $filter, and $$NOW for timestamps. I use it for data migrations and derived fields. Classic operators like $inc and $push aren't available inside the pipeline, and literal strings starting with $ need $literal.

Open in topic →

Predict the result: the stages are swapped

mongosh
db.orders.aggregate([
  { $group: { _id: "$customerId", totalOrders: { $sum: 1 } } },
  { $match: { status: "shipped" } }
]).toArray()
Show answer

[]: an empty array, with no error.

What’s happening
  1. $group runs first over all 8 orders and outputs 5 documents shaped { _id: <customerId>, totalOrders: <n> }.
  2. Those documents have no status field: $group only outputs _id and the accumulators you asked for.
  3. $match: { status: "shipped" } compares a missing field with "shipped", which is false for every document, so nothing survives.
  4. MongoDB doesn't warn you, because a missing field is a perfectly legal thing to match on. The fix is to put the $match first (it then acts like SQL WHERE) or, if you meant to filter groups, match on a field the group produced ({ totalOrders: { $gte: 2 } }, which acts like HAVING).
Open in topic →

What is the aggregation pipeline?

Show answer

"It's MongoDB's framework for computed queries: you pass aggregate() an array of stages, and documents flow through them in order. Each stage takes the previous stage's output: $match filters, $group groups and computes accumulators, $project and $addFields reshape, $sort, $skip and $limit order and page, $lookup joins, $unwind flattens arrays. Stage order is the order of work, so you filter early, and the server's optimiser also reorders some stages for you. It returns a cursor, and it replaced map-reduce, which is deprecated since 5.0."

Open in topic →

Spot the bug: why is this pipeline slow?

mongosh
db.users.aggregate([
  { $project: { name: 1, city: 1, score: 1 } },
  { $sort: { score: -1 } },
  { $match: { city: "Toronto" } },
  { $limit: 10 }
])
Show answer

On paper it sorts every user before filtering; in practice MongoDB's optimiser moves the $match to the front, because it only uses a field (city) that the earlier $project didn't compute.

What’s happening
  1. As written, $project and $sort would process all 100,000 users before $match threw most of them away.
  2. The optimiser checks each $match filter: if it doesn't depend on a field created by an earlier projection stage, it moves that filter in front of the projection. city is an original field, so the $match becomes stage one and can use an index on city.
  3. explain() on this pipeline confirms it: the initial cursor's filter is { city: { '$eq': 'Toronto' } } with an IXSCAN, the $project was folded into the cursor's projection, and the only stage left after it is $sort with limit: 10 coalesced in.
  4. Don't rely on it, though. A filter on a computed field (say ageBand from an $addFields) can't move, and the reordering can't get past stages like $group or $unwind. Write $match first yourself. Pipeline performance shows the explain output for this.
Open in topic →

Why is $match first and $project last?

Show answer

"$match early because every document it removes is work no later stage has to do, and a $match at the start of the pipeline can use an index, like a find() would. $project belongs at the end, to shape the output for the client. Putting a $project early to 'slim documents down' is an old habit: the server already tracks which fields later stages need and only fetches those, and the docs say an early $project is unlikely to improve performance."

Open in topic →

Predict the result: averaging a field that isn't always there

mongosh
db.vals.insertMany([ { a: 10 }, { a: 20 }, { a: null }, { } ])
db.vals.aggregate([ { $group: { _id: null, avg: { $avg: "$a" }, sum: { $sum: "$a" }, n: { $sum: 1 } } } ])
Show answer

{ _id: null, avg: 15, sum: 30, n: 4 }.

What’s happening
  1. Four documents enter the single group, so n counts all four.
  2. $avg ignores non-numeric values: null and the missing field don't count, so it averages 10 and 20 → 15, not 30 / 4 = 7.5.
  3. $sum also ignores non-numbers, giving 30. (Had every value been missing, $sum would return 0 and $avg would return null.)
  4. SQL's AVG behaves the same way with NULLs. If you want missing values to count as zero, write $avg: { $ifNull: ["$a", 0] }.
Open in topic →

How does $group work, and why is _id required?

Show answer

"$group buckets documents by the _id expression (a field, a document of fields for a composite key, or null for one overall group) and outputs one document per bucket containing _id and the accumulators: $sum, $avg, $min, $max, $push, $addToSet, $first/$last, and newer ones like $topN and $median. _id is required because it is the grouping key; without it there's nothing to group by. Any field you don't accumulate is dropped, the output isn't sorted, and $first/$last only make sense after a $sort."

Open in topic →

Predict the result: $limit before $sort

mongosh
db.products.aggregate([ { $limit: 3 }, { $sort: { price: -1 } }, { $project: { _id: 0, name: 1, price: 1 } } ])
Show answer
Output
[
  { name: 'MacBook Air', price: 1299 },
  { name: 'ThinkBook 14', price: 899 },
  { name: 'Pixel 10', price: 799 }
]
What’s happening
  1. $limit: 3 runs first and passes whichever three documents the collection scan produced first. Here that's natural (insertion) order: products 1, 2 and 3. That order isn't guaranteed either.
  2. $sort then orders only those three by price. The iPhone (1099) isn't in the result even though it's the second most expensive product, because it never got past the $limit.
  3. To get "the three most expensive products", $sort must come before $limit. Since stage order is the order of work, the optimiser won't swap them for you: it would change the answer.
Open in topic →

Predict the result: $addFields fields referring to each other

mongosh
db.orders.aggregate([
  { $match: { _id: 2 } },
  { $addFields: {
      total: { $sum: { $map: { input: "$items", in: { $multiply: ["$$this.qty", "$$this.unitPrice"] } } } },
      withTax: { $multiply: ["$total", 1.13] }
  } },
  { $project: { _id: 0, total: 1, withTax: 1 } }
])
Show answer

[ { total: 88, withTax: null } ].

What’s happening
  1. Every expression in one $addFields is evaluated against the document as it entered the stage.
  2. total is computed as 39 + 49 = 88 ($$this is the default variable name in $map when you don't give as).
  3. withTax reads "$total" from the incoming document, where total doesn't exist yet. A missing value in $multiply gives null.
  4. Fix: compute withTax in a second $addFields/$set stage, or inline the expression, or use $let to name the intermediate value once.
Open in topic →

Predict the result: is $lookup an inner join?

How many documents does this return, and what does Zara's look like?

mongosh
db.customers.aggregate([
  { $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } },
  { $project: { name: 1, n: { $size: "$orders" } } }
])
Show answer

6 documents, one per customer, and Zara's is { _id: 6, name: 'Zara', n: 0 }.

What’s happening
  1. $lookup never removes or duplicates input documents: 6 customers in, 6 out.
  2. Each gets an orders array: Rohit 2, Maya 2, Liam 2 (including the cancelled one, because this lookup doesn't filter), Sofia 1, Noah 1, Zara none.
  3. Zara's array is [], so $size gives 0. That's the left outer join behaviour my notes point out.
  4. The join only turns into an inner join if you add a stage that drops the empty arrays, which $unwind does by default. That's the trap the next topic is about.
Open in topic →

How do you join collections in MongoDB?

Show answer

"With $lookup in an aggregation pipeline. Give it from, localField, foreignField and as, and each input document gets an array of matching documents from the other collection. It's a left outer join: no match gives an empty array, not a dropped document. For extra conditions, use the let/pipeline form, or localField/foreignField plus pipeline since 5.0. Index the foreignField. Then usually $unwind the result, with preserveNullAndEmptyArrays if you want to keep the unmatched documents. And if you're joining on every read, that's a sign the data should probably be embedded instead."

Open in topic →

Predict the result: counting line items

mongosh
db.orders.aggregate([ { $unwind: "$items" }, { $count: "lines" } ])
Show answer

[ { lines: 13 } ].

What’s happening
  1. The 8 orders have 2, 2, 2, 1, 2, 1, 2, 1 items.
  2. $unwind emits one document per element: 2 + 2 + 2 + 1 + 2 + 1 + 2 + 1 = 13.
  3. $count counts the documents reaching it, so the answer is the number of line items, not orders.
  4. The cheaper way to get the same number without multiplying documents: { $group: { _id: null, lines: { $sum: { $size: "$items" } } } }.
Open in topic →
InterviewCh 19 $unwind

What does $unwind do, and what's preserveNullAndEmptyArrays for?

Show answer

"$unwind deconstructs an array field: one output document per element, with the field replaced by that element and every other field copied. You use it to group across array elements, or to flatten the array $lookup produces. By default it drops documents whose array is empty, null or missing. After a $lookup that turns the left join into an inner join, so you set preserveNullAndEmptyArrays: true to keep them. Watch the multiplication: big arrays, or two unwinds in a row, can blow up the document count."

Open in topic →

Predict the result: a value on a boundary

With boundaries: [0, 50, 500, 1000] and default: "other", which bucket does a product priced exactly 500 go into, and one priced exactly 1000?

Show answer

500 goes into the 500 bucket; 1000 goes into "other".

What’s happening
  1. Each range includes its lower boundary and excludes its upper one: [500, 1000) contains 500.
  2. 1000 is the upper boundary of the last range, so it's excluded from it, and there's no range starting at 1000.
  3. So 1000 falls to the default bucket. If you want 1000 included, make the last boundary 1001 (for integers) or add another boundary.
Open in topic →

Predict the result: an empty facet

mongosh
db.products.aggregate([
  { $match: { category: "Tablets" } },
  { $facet: { items: [ { $limit: 5 } ], total: [ { $count: "n" } ] } }
])
Show answer

[ { items: [], total: [] } ]: one document with two empty arrays.

What’s happening
  1. No product has category "Tablets", so zero documents reach $facet.
  2. $facet still outputs exactly one document. It always does, which makes the response shape predictable for the client.
  3. items is [] because $limit passed nothing. total is [] too, not [ { n: 0 } ]: $count emits nothing when it counted nothing.
  4. That's why the flattening example above wraps the count in $ifNull: [..., 0].
Open in topic →
InterviewCh 19 $facet

When would you use $facet?

Show answer

"When one request needs several aggregations over the same filtered set, typically a faceted search page: the results page, the total count, and counts per category and price band. You $match once (and that's where indexes help), then $facet runs a sub-pipeline per output and returns a single document with one array per facet. Two things to remember: the sub-pipelines can't use indexes, and the whole result is one document, so it must stay under 16 MB. Limit anything that returns documents."

Open in topic →

Predict the result: will this $match move?

mongosh
db.users.aggregate([
  { $addFields: { ageBand: { $multiply: [ { $floor: { $divide: ["$dob.age", 10] } }, 10 ] } } },
  { $match: { ageBand: 30, city: "Toronto" } }
])
Show answer

The optimiser splits the $match: { city: "Toronto" } moves before $addFields (and can use an index on city); { ageBand: 30 } stays after it.

What’s happening
  1. The optimiser looks at each condition of the $match separately.
  2. city is an original field, not touched by the $addFields, so that condition can run first, in the query layer.
  3. ageBand only exists after the $addFields has computed it, so that part of the filter must stay behind it. explain() shows exactly this: the cursor filter is { city: { '$eq': 'Toronto' } } (an IXSCAN on the city index), followed by $addFields and then $match: { ageBand: { '$eq': 30 } }.
  4. If you need the age filter to use an index too, write it against the original field: { "dob.age": { $gte: 30, $lt: 40 } }. Filters on computed values can never use an index.
Open in topic →

How do you optimise an aggregation pipeline?

Show answer

"Reduce the documents as early as possible and let the indexes do the reducing. Put $match first, on indexed fields, followed by $sort and $limit if you need them, because at the start of the pipeline those run like a find() and can use an index, including a compound index that serves the sort. Avoid unnecessary $unwind, index $lookup's foreignField, and keep $facet inputs small. Put $project at the end: the server already fetches only the fields the pipeline needs. Then verify with explain('executionStats'): look for IXSCAN, keys and docs examined close to the number returned, and no usedDisk. For heavy reports, pre-aggregate with $merge."

Open in topic →

Aggregation pipeline vs map-reduce?

Show answer

"Map-reduce runs JavaScript map and reduce functions inside the server: map emits key/value pairs, reduce folds the values per key. It was deprecated in MongoDB 5.0 in favour of the aggregation pipeline, which uses native stages the optimiser understands, can use indexes, and is far faster: in my test, counting 100,000 documents per city took about 20 ms with $group and nearly a second with map-reduce. Anything map-reduce did maps onto $group, $project and $merge or $out for writing results, and $function/$accumulator exist for the rare custom logic."

Open in topic →

Why do we need indexes, and what do they cost?

Show answer

"Without an index, MongoDB has to do a collection scan: read every document and test it. An index is a sorted B-tree of field values pointing at documents, so equality, ranges and sorts on those fields become a short walk through the tree. Every collection has a unique _id index by default. The cost is on writes and memory: each insert, update or delete has to maintain every index, and indexes take disk and should fit in RAM. In my test, four extra indexes made bulk inserts about 50% slower. So you index for your actual query patterns, check with explain, and drop indexes nothing uses."

Open in topic →

Read the numbers

An explain("executionStats") shows nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 20, and a SORT stage above the FETCH. The query was find({ status: "active" }).sort({ createdAt: -1 }).limit(20). Is it well indexed?

Show answer

No. The counts look perfect, but the SORT stage gives it away, and the counts can't be right for this plan.

What’s happening
  1. A SORT stage means the order came from an in-memory sort, not from an index. To sort, the server must have read all active documents first, so totalKeysExamined would normally be the number of active documents, not 20.
  2. If it really is 20, then only 20 documents are active, and the query is fine for now and will degrade as data grows.
  3. Either way, the right index is { status: 1, createdAt: -1 }: equality first, then the sort field. Then the plan becomes LIMIT ← FETCH ← IXSCAN with no SORT, and it reads exactly 20 keys however many active documents there are. That's the ESR rule, next but one.
Open in topic →

How do you investigate a slow MongoDB query?

Show answer

"Run it with explain('executionStats'). I check the winning plan's stages, COLLSCAN means no usable index and a SORT stage means a blocking in-memory sort, then compare nReturned with totalKeysExamined and totalDocsExamined. If documents examined is much bigger than documents returned, the index isn't selective enough or doesn't include all the filter fields. allPlansExecution shows the rejected candidates, and hint() lets me measure alternatives. To find slow queries in the first place, I use the profiler or the slow-query log, which logs operations over 100 ms by default."

Open in topic →

Which queries can use the index?

With an index on { a: 1, b: 1, c: 1 }, which of these can use it efficiently: (1) { a: 5 }, (2) { b: 5 }, (3) { a: 5, c: 7 }, (4) { a: 5, b: { $gt: 1 } } sorted by c, (5) { c: 7, b: 2, a: 1 }?

Show answer

1, 3 (partly), 4 (partly) and 5. Not 2.

What’s happening
  1. { a: 5 } uses the prefix a: tight bounds.
  2. { b: 5 } has no a, so it isn't a prefix: no efficient use (at best a full index scan).
  3. { a: 5, c: 7 } uses a for the bounds; c can only be checked against index keys inside the a = 5 block, because b is skipped. Better than nothing, not tight.
  4. { a: 5, b: { $gt: 1 } } uses a and b for bounds, but sorting by c needs an in-memory SORT: after a range on b, the entries are ordered by b first, not by c. That's the ESR problem in the next topic.
  5. The order of fields in the query doesn't matter. { c, b, a } is the same filter as { a, b, c } and uses all three fields. Only the order in the index matters.
Open in topic →

Single-field vs compound indexes: why does field order matter?

Show answer

"A compound index is sorted by its first field, then by the second within equal first values, and so on, like a phone book by surname then first name. So it supports queries on any leading prefix of its fields, but not on a later field alone. It can also provide sort order: the same field order and directions as the index, or the exact reverse. So I put fields that are always filtered by equality first, then the sort fields, then range fields. That's the ESR rule. One well-designed compound index often replaces several single-field ones."

Open in topic →

Design the index

Queries: find({ tenantId: 42, status: "open", createdAt: { $gte: lastWeek } }).sort({ priority: -1 }). Which index?

Show answer

{ tenantId: 1, status: 1, priority: -1, createdAt: 1 }.

What’s happening
  1. Equality: tenantId and status are exact matches, so they go first (either order; choose the one other queries can use as a prefix, usually tenantId).
  2. Sort: priority: -1 next, in the direction of the sort (or its reverse, if all fields flip), so results come out ordered without a SORT stage.
  3. Range: createdAt last; it's filtered on index keys while walking in priority order.
  4. Putting createdAt before priority would give tighter bounds but force an in-memory sort of every open ticket from the last week. Fine if that's always a few dozen, a problem if it's 100,000.
Open in topic →

What is the ESR rule?

Show answer

"It's the rule of thumb for compound index field order: Equality fields first, then Sort fields, then Range fields. Equality fields narrow the scan to one contiguous part of the index; the sort fields next mean that part is already in the order you asked for, so there's no in-memory SORT stage and a limit can stop early; range fields last are filtered while walking. If you put the range before the sort, you get tighter bounds but lose the order and pay for a blocking sort. In my test, a page of 20 read 21 index keys with the ESR order and almost 17,000 with the range first."

Open in topic →

Spot the bug: the partial index is never used

mongosh
db.orders.createIndex({ customerId: 1 }, { partialFilterExpression: { status: { $in: ["paid", "shipped"] } } })
db.orders.find({ customerId: 2 })
Show answer

The query doesn't include a condition on status, so the planner can't prove every match is in the index. It ignores the partial index and scans.

What’s happening
  1. The index only contains paid and shipped orders.
  2. find({ customerId: 2 }) asks for all of customer 2's orders, including any pending or cancelled ones, which aren't in the index.
  3. Using the index could silently drop results, so the planner won't.
  4. Fix: add the filter to the query, find({ customerId: 2, status: { $in: ["paid", "shipped"] } }) (or a condition that implies it, such as status: "paid"), or use a full index if the application needs all statuses.
Open in topic →

What are unique and partial indexes for?

Show answer

"A unique index enforces that no two documents share the key: the database rejects the write with E11000, atomically, so there's no check-then-insert race. Missing fields count as null, so only one document can lack the field. A partial index only indexes documents matching a filter expression, so it's smaller and cheaper to maintain, but a query only uses it if its filter implies the index's filter. Put together, a partial unique index gives 'unique if present', e.g. an optional phone number."

Open in topic →

Predict the result: the TTL that never fires

mongosh
db.events.createIndex({ ts: 1 }, { expireAfterSeconds: 60 })
db.events.insertOne({ type: "login", ts: Date.now() })

Two minutes later, is the document still there?

Show answer

Yes, and it stays there forever.

What’s happening
  1. Date.now() returns a number (milliseconds since 1970), not a BSON date.
  2. The TTL monitor only expires documents whose indexed field is a date or an array of dates. A number is silently ignored, exactly like the string-date document in the main example.
  3. Use new Date() in mongosh/Node (or datetime in Python) so the value is stored as a BSON date. Schema validation with bsonType: "date" on the field catches this at insert time.
Open in topic →

How does a TTL index work, and how precise is it?

Show answer

"It's a single-field index on a date field with expireAfterSeconds. A background TTL monitor on the primary runs every 60 seconds by default and deletes documents whose date plus expireAfterSeconds has passed. With expireAfterSeconds: 0 you store the exact expiry time per document. It isn't precise: deletion happens on the next pass, up to a minute late or more under load. In my test, a 10-second TTL deleted documents anywhere from 14 to 60 seconds after insertion. So for tokens you still check the expiry in the query. Only BSON dates expire; missing fields, strings and numbers never do, and compound indexes can't be TTL."

Open in topic →

What is a multikey index?

Show answer

"An index on an array field. MongoDB stores one index entry per array element, all pointing at the same document, and marks the index multikey automatically. That makes 'array contains value' queries fast, including on fields of embedded documents like items.productId. The costs: the index is bigger, roughly one entry per element; a compound index can include only one array per document ('cannot index parallel arrays'); it can't cover the array field; and you need $elemMatch when several conditions must hold on the same element."

Open in topic →

Is this query covered?

Index: { email: 1 }. Query: db.users.find({ email: "user5@example.com" }, { email: 1 }).

Show answer

No. The projection returns _id by default, and _id isn't in the { email: 1 } index.

What’s happening
  1. The filter field email is in the index, and the projection asks for email, which is in the index too.
  2. But the projection also includes _id, because _id is always returned unless excluded. My notes: "_id will always be returned… if you don't want it, set it to 0".
  3. To fetch _id, the server must load the document: a FETCH stage, 1 document examined.
  4. Either project { _id: 0, email: 1 }, or build the index as { email: 1, _id: 1 } if you need _id too.
Open in topic →

What is a covered query?

Show answer

"A query whose filter and projection fields are all in one index, so MongoDB answers it from the index alone without loading documents. In explain you see PROJECTION_COVERED and totalDocsExamined: 0. The usual mistake is forgetting _id: it's returned by default, so you exclude it or include it in the index. Multikey indexes can't cover the array field itself. It's worth designing for on hot read paths; in my test a 17,000-result query took 3 ms covered and 12 ms with fetches, with everything cached."

Open in topic →

How do you do full-text search in MongoDB?

Show answer

"The built-in option is a text index: create one over the string fields, query with $text: { $search }. It stems words and drops stop words, ORs the terms, supports -term to exclude and quoted phrases, and gives a textScore for ranking. There's only one text index per collection, which is why the query names no field. For serious search (typos, autocomplete, relevance tuning, facets, vector search) you use MongoDB Search with the $search stage, which runs on Lucene in a separate mongot process: on Atlas, and on self-managed deployments since 2025–26."

Open in topic →

When would you use a wildcard index?

Show answer

"When documents have fields you can't predict, like product attributes that differ per category or user-defined custom fields, and you need to query any of them. { 'specs.$**': 1 } indexes every field under specs, so one index acts like a single-field index on each attribute. But a query uses it for one field at a time, it can't provide a sort on another field, and it can't be unique or TTL. For known, frequent query shapes, normal compound indexes are still better, and since 7.0 a compound wildcard index can combine fixed fields with the wildcard."

Open in topic →

Foreground vs background index builds?

Show answer

"That's the pre-4.2 distinction. A foreground build was fast but locked the database for its whole duration; a background build allowed reads and writes but was slower and produced a less compact index. Since MongoDB 4.2 there's one optimised build: an exclusive lock only briefly at the start and end, concurrent reads and writes in between, with writes captured in a side table, and the background option is ignored. On replica sets, members build in parallel and the primary commits once the commit quorum is ready. For maintenance, reIndex is deprecated and standalone-only, and compact is only for reclaiming disk after big deletes, not routine tuning. I use hidden indexes and $indexStats to retire unused indexes safely."

Open in topic →

Embed or reference?

A blog has posts and comments. A post page shows the post and its comments. Some posts get 5 comments, a few viral ones get 200,000. Users also have a "my comments" page. Embed the comments in the post?

Show answer

Not entirely. Reference them (a comments collection with postId, indexed), and optionally embed a subset: the latest 10 comments in the post for fast first page loads.

What’s happening
  1. Read together: yes, the post page shows comments, which argues for embedding.
  2. But the count is unbounded: 200,000 comments of a few hundred bytes would break the 16 MB limit, and long before that every new comment rewrites a huge document (measured in the next topic).
  3. The "my comments" page reads comments on their own, across posts, which a separate collection with an index on { authorId: 1, createdAt: -1 } serves directly.
  4. The subset pattern gives most of the read benefit of embedding: $push with $slice: -10 keeps the last 10 in the post, and the full list is paged from comments.
Open in topic →

Embedding vs referencing: how do you decide?

Show answer

"I start from the access patterns: data read together is stored together. I embed when the child belongs to one parent, is read with it, and is bounded, like order lines or a user's addresses, which gives one-read access and atomic updates. I reference when the child is shared, read on its own, changes independently, or grows without bound, like a customer across orders or comments on a viral post, and join with $lookup or a second query. Often it's a mix: reference plus a few copied fields for display, or the latest N embedded and the rest in their own collection. And I keep the 16 MB document limit in mind."

Open in topic →

What's the 16 MB limit and how do you design around it?

Show answer

"A single BSON document can be at most 16 MiB, enforced on inserts and on updates that would grow a document past it. You rarely hit it with normal data; you hit it with unbounded arrays, like embedding every comment or every reading in one parent. Long before the limit, those documents get slow, because every update rewrites the whole document and every read ships it. So I bound arrays (subset pattern), move unbounded children into their own collection, bucket time series, and use GridFS or object storage for large files."

Open in topic →

Spot the problem

A product's name, price and category are embedded in every order line, and the team runs updateMany({ "items.productId": 7 }, { $set: { "items.$[i].price": 25 } }, { arrayFilters: [{ "i.productId": 7 }] }) whenever a price changes. What's wrong?

Show answer

It rewrites history. A price change must not alter orders that were already placed at the old price.

What’s happening
  1. The price in an order line is a snapshot: what the customer actually paid. Copying it is right; updating it later is wrong.
  2. The update silently changes past revenue, invoices and refunds for every order containing product 7.
  3. name is a judgement call (show the name at the time of sale, or the current one?), but price is not.
  4. Correct design: keep productId plus the snapshot fields (unitPrice, and name as sold), and read the current product from products when you need current data.
Open in topic →

When would you normalise in MongoDB?

Show answer

"Embedding is the default, but I normalise when duplicated data would have to be kept in sync: data that changes often and appears in many documents, like a customer's email or address; many-to-many relationships; unbounded children; and entities read on their own. In my test, changing one customer's address meant updating 787 embedded copies instead of one document, while the read with $lookup was only a fraction of a millisecond slower. I also separate snapshots from current values: the price or shipping address on an order is a historical copy and should never be updated."

Open in topic →

How do you model one-to-many and many-to-many in MongoDB?

Show answer

"By cardinality and access pattern. One-to-few I embed. One-to-many I usually reference from the child, the child stores the parent's id with an index, because that scales and keeps the parent small; an array of ids in the parent only works if it's bounded. One-to-squillions, like logs, always child-to-parent. Many-to-many I model with an array of ids on the side with the smaller fan-out, index it, and $lookup in either direction; if the relationship has its own attributes, a separate junction collection, like SQL."

Open in topic →

Name some MongoDB schema design patterns.

Show answer

"Subset: embed only the hot part, like the latest 10 reviews, and keep the full list in its own collection. Computed: maintain aggregates on write, like a review count and rating sum with $inc, instead of recomputing on every read. Extended reference: copy a few fields of a referenced document to avoid $lookup. Bucket: group time series data per entity per time window; time series collections do that automatically since 5.0. Outlier: special handling for the few huge documents. Attribute: key/value pairs with one compound index for many optional fields. Polymorphic, schema versioning with lazy migration, and tree patterns like materialised paths. They all trade some write complexity or duplication for faster, simpler reads."

Open in topic →

Predict the result: moderate validation

A collection has a validator requiring email to be a string, with validationLevel: "moderate". Document A has email: 42 (inserted before the validator existed). What happens to updateOne({ _id: A }, { $set: { visits: 1 } }) and to insertOne({ email: 42 })?

Show answer

The update succeeds; the insert fails.

What’s happening
  1. moderate only validates updates to documents that currently pass the rules. Document A already fails (its email is a number), so updates to it aren't checked, and the $set goes through.
  2. Inserts are always validated (unless validationLevel: "off"), so a new document with email: 42 is rejected with "Document failed validation".
  3. Same behaviour as the legacy example above. Switch to strict once the existing bad documents have been fixed.
Open in topic →

Does MongoDB support schemas?

Show answer

"Yes, optionally, with schema validation. You attach a validator to a collection, usually $jsonSchema, with required fields, BSON types, ranges, enums and patterns; any query expression, including $expr for cross-field rules, also works. validationLevel is strict or moderate, which skips updates to documents that were already invalid so you can add rules to existing data, and validationAction is error, warn to only log, or errorAndLog since 8.1. Since 5.0 the error explains exactly which rules failed. What it can't do is uniqueness or referential integrity: those need unique indexes and application logic or transactions. I use it as a safety net under the application's own validation."

Open in topic →

Is MongoDB ACID?

Show answer

Yes, at two levels. A write to a single document has always been atomic, isolated and durable (with journaling and the right write concern), including all its embedded arrays and sub-documents. Since 4.0 on replica sets and 4.2 on sharded clusters, multi-document transactions are ACID too, with snapshot isolation. The design advice is to model data so most operations touch one document and need no transaction, and use transactions for the cases that genuinely span documents, like moving money between two accounts.

Open in topic →

Predict the stock

Product 2 has stock: 5. Eight clients run this at the same time. What's the final stock, and how many clients think they sold one?

mongosh
const p = db.products.findOne({ _id: 2 });
sleep(200);   // the app does some work
if (p.stock > 0) db.products.updateOne({ _id: 2 }, { $inc: { stock: -1 } });
Show answer

The final stock is -3, and all eight think they sold one.

What’s happening
  1. All eight findOne calls run before any update lands, so every client reads stock: 5 and passes the p.stock > 0 check.
  2. This time the write is $inc: -1, not $set: p.stock - 1, so there's no lost update: each decrement is applied atomically to the current value.
  3. Eight decrements of 5 gives 5 → -3. The $inc fixed the lost-update bug but not the oversell, because the check still happened in the app on a stale value.
  4. The fix is to move the check into the filter: updateOne({ _id: 2, stock: { $gt: 0 } }, { $inc: { stock: -1 } }), which stops at exactly 0.
Open in topic →

How do transactions work in MongoDB?

Show answer

They're session-based: start a session, startTransaction, run the operations with that session, then commit or abort. They give snapshot isolation and all-or-nothing commits across documents and collections, on replica sets since 4.0 and sharded clusters since 4.2. The limits to remember: they need a replica set or sharded cluster, by default they must finish within 60 seconds, and conflicting writes abort with a TransientTransactionError that you're expected to retry, which the drivers' withTransaction helper does for you. And they cost more than a single-document write, so model to avoid them where you can.

Open in topic →

When would you avoid a transaction in MongoDB?

Show answer

When the change fits in one document, because single-document writes are already atomic, so I'd embed related data or use a conditional update instead. When the same documents are updated at high frequency, because concurrent transactions on hot documents abort each other with write conflicts and spend their time retrying. And for long-running work, because a transaction that stays open holds its write locks, keeps an old snapshot in the cache and is killed after 60 seconds by default. Reads don't need a transaction unless they must see several documents at one consistent point in time.

Open in topic →

What is a replica set and how does failover work?

Show answer

A replica set is a primary plus secondaries holding the same data. All writes go to the primary, which records them in its oplog; secondaries pull the oplog and apply it. Members heartbeat each other every 2 seconds, and if the primary isn't heard from for the election timeout, 10 seconds by default, a secondary calls an election and needs votes from a majority of voting members to win. Drivers discover the topology from the connection string and route writes to the new primary, and retryable writes retry once across the failover. You use an odd number of voting members, three or five, so a majority can still be formed when a member is lost. It gives high availability and read scaling with secondary reads; it doesn't give write scaling, which needs sharding.

Open in topic →

What is the oplog?

Show answer

It's a capped collection, local.oplog.rs, on every replica set member that records every change to data as an idempotent operation, ordered by timestamp. The primary writes to it as part of each write; secondaries tail their sync source's oplog and apply the entries, which is all replication is. Its size sets the "oplog window": how far behind a secondary can fall, or how long it can be offline, and still catch up by replaying entries instead of a full resync. It also powers change streams and point-in-time backups with mongodump --oplog.

Open in topic →

Explain write concern w: 0, 1 and majority.

Show answer

Write concern says how many members must acknowledge a write before the server replies. w: 0 is fire-and-forget: fastest, but you see no errors and the write might never happen. w: 1 waits for the primary: fast, but if the primary fails before a secondary copies the write, that write is rolled back and lost even though it was acknowledged. w: "majority" waits for a majority of voting data-bearing members: a majority-acknowledged write survives any failover, because any new primary must come from that majority. j: true also requires the journal on disk. "majority" has been the default since 5.0, and a write concern timeout or error doesn't undo the write, it only means the requested durability wasn't confirmed.

Open in topic →

What's the difference between read concern and read preference?

Show answer

Read concern is about which data a read may see: local returns the node's latest data, which might later be rolled back; majority returns only data acknowledged by a majority, which can't be; linearizable also guarantees you see every majority write that completed before the read started; snapshot gives a consistent point-in-time view, used in transactions. Read preference is about which member serves the read: primary by default, or primaryPreferred, secondary, secondaryPreferred or nearest. Reading from secondaries spreads load or reduces latency, but the data can be behind, so it's for analytics or geo-local reads, not for "read your own write" unless you use a causally consistent session.

Open in topic →

Replica set vs sharding?

Show answer

A replica set is the same data copied to several members: it gives high availability and automatic failover, and secondary reads, but every member holds everything and all writes go to one primary. Sharding splits the data across several replica sets by a shard key, behind mongos routers and a config server replica set, so storage and write throughput scale with the number of shards. In production you use both: every shard is itself a replica set. Shard when the data or the write load outgrows one replica set, not before, because it adds operational complexity and makes the shard key a long-term design decision.

Open in topic →

How do you choose a shard key?

Show answer

I look at the queries and write pattern first. The key should have high cardinality, no hugely common values, and shouldn't increase monotonically, otherwise all inserts go to one shard. It should also appear in the most frequent queries, so mongos can target one shard instead of scattering to all. A hashed key spreads monotonic values like timestamps or ObjectIds evenly but makes range queries on that field scatter-gather; a compound key like { customerId: 1, createdAt: 1 } often gives both spread and locality. Since 7.0 analyzeShardKey measures cardinality, frequency and monotonicity on real data, and since 5.0 you can reshard if you got it wrong, but resharding copies the whole collection.

Open in topic →

Pick the shard key

A ride-hailing app stores trips: { _id: ObjectId, riderId, driverId, city, startedAt, ... }. 90% of queries are "trips for this rider, newest first". There are 30 cities, 5 million riders, and writes are 20,000 trips a minute. Which shard key: { city: 1 }, { _id: 1 }, { startedAt: "hashed" } or { riderId: 1, startedAt: 1 }?

Show answer

{ riderId: 1, startedAt: 1 }.

What’s happening
  1. { city: 1 } has cardinality 30 and very uneven frequency (one big city could hold 20% of trips). It can't use more than 30 chunks and the big cities become jumbo chunks.
  2. { _id: 1 } with ObjectIds is monotonic: every new trip goes to the top chunk on one shard, so 20,000 writes a minute hit one machine.
  3. { startedAt: "hashed" } spreads writes evenly, but "trips for this rider" doesn't contain the key, so every one of the main queries is scatter-gather.
  4. { riderId: 1, startedAt: 1 } has 5 million leading values (high cardinality, low frequency), isn't monotonic because riders are random, and the main query (riderId plus a sort on startedAt) targets one shard and reads one contiguous range. It's also supported by the key's own index.
Open in topic →

How do you back up MongoDB?

Show answer

For small and medium deployments, mongodump and mongorestore: a logical BSON export plus index definitions, flexible down to one collection, and on a replica set mongodump --oplog with mongorestore --oplogReplay gives a consistent point-in-time copy while writes continue. It's slow for large data sets, because restore rebuilds every index, and it isn't the recommended way to back up a busy sharded cluster. For large or critical systems I'd use physical backups: filesystem or volume snapshots of a secondary with journaling on, or managed continuous backups in Atlas or Ops Manager, which add point-in-time restore from the oplog. And whatever the method, restores get tested regularly.

Open in topic →

How does authentication work in MongoDB?

Show answer

You enable access control with --auth or security.authorization, create the first admin user in the admin database through the localhost exception, and from then on clients authenticate as user plus authentication database. The default mechanism is SCRAM-SHA-256, a salted challenge-response: the password never crosses the network and the server stores only derived keys, so a leaked system.users doesn't reveal passwords. Other mechanisms are x.509 client certificates, and in Enterprise or Atlas, LDAP, Kerberos, OIDC and AWS IAM. Members of a replica set or sharded cluster also authenticate to each other, with a keyfile or x.509, which is internal authentication. And authentication only matters if TLS protects the connection and the port isn't open to the internet.

Open in topic →

How does authorisation work in MongoDB?

Show answer

It's role-based. Privileges are actions on resources, a database, a collection or the cluster; roles bundle privileges and can inherit other roles; users are granted roles, and a request is allowed only if one of the user's roles grants that action on that resource. Built-in roles cover most needs, read, readWrite, dbAdmin, userAdmin, clusterMonitor, backup, root, and custom roles with createRole can narrow access to single collections or specific actions. For field-level restrictions you expose a view and grant access only to the view. Apps get their own least-privilege users, and userAdmin is treated as powerful as root, because it can grant any role.

Open in topic →
InterviewCh 23 TLS

How do you secure MongoDB in production?

Show answer

Network first: bind to private interfaces only, firewall the port, never expose it to the internet. Turn on access control and give each app and person a least-privilege user. Require TLS for every connection, with certificates from a CA the clients verify, and use keyfiles or x.509 for authentication between replica set members. Encrypt sensitive fields client-side with CSFLE or Queryable Encryption if the database operators or backups shouldn't see them, and use encryption at rest, which is the Enterprise encrypted storage engine or Atlas, or disk encryption. Then audit, keep versions patched and test backups. Atlas does most of this by default: TLS is always on and IP access lists are required.

Open in topic →

What's the difference between CSFLE and Queryable Encryption?

Show answer

Both encrypt sensitive fields in the client, so the server, its logs, the oplog and backups only ever hold ciphertext, with data keys protected by a master key in a KMS. CSFLE, since 4.2, supports equality queries only on deterministically encrypted fields, and deterministic encryption leaks which documents share a value. Queryable Encryption, GA since 7.0, always uses randomised encryption with encrypted index structures, and supports equality, range since 8.0, and prefix, suffix and substring since 9.0. QE is the recommendation for new apps; CSFLE still fits when you need per-tenant keys for the same field. Automatic encryption needs Enterprise or Atlas; explicit encryption works on Community. Neither replaces TLS or encryption at rest; they protect against people who can see the server.

Open in topic →

How do you find slow queries in MongoDB?

Show answer

I start with the slow query log, which records every operation over slowms, 100 ms by default, with its plan summary, keys and documents examined and duration, or with the profiler at level 1 to get the same data as queryable documents in system.profile. I look for COLLSCAN, a high docsExamined to nreturned ratio, and in-memory sorts, then confirm with explain("executionStats") and fix with an index or a query change. For live problems, $currentOp shows what's running and waiting, and killOp stops a runaway operation. serverStatus, mongostat and mongotop show overall load. In Atlas, the Query Profiler and Performance Advisor do this continuously. Level 2 profiling records everything, so it's only for short debugging sessions.

Open in topic →

How do you connect to MongoDB from Node.js?

Show answer

With the official mongodb driver: create one MongoClient per process from a connection string, connect at startup and share it everywhere, because it's a pool and topology monitor, not a single connection. It discovers replica set members, routes writes to the primary, retries a failed write once after a failover since retryable writes are on by default, and enforces maxPoolSize. Operations return promises, find returns a lazy cursor, server errors are MongoServerError with a numeric code, like 11000 for duplicate keys, and you close the client on shutdown. Mongoose sits on top when you want schemas and models.

Open in topic →

Mongoose or the native driver?

Show answer

Mongoose gives you schemas, casting, defaults, validation, middleware, populate and a model API, which suits apps with many developers and a stable domain model. The cost is a layer of abstraction: documents are heavier objects, some behaviours are implicit, like dropping unknown fields, casting, and validation running on save but not on updates by default, and you need lean() for read-heavy paths. The native driver is thinner and faster and exposes every server feature directly; with TypeScript types and database-side $jsonSchema validation it covers much of what Mongoose offers. I'd pick Mongoose for a typical CRUD app and the driver for performance-critical services, data pipelines or libraries.

Open in topic →

How does validation work in Mongoose?

Show answer

Validators are declared in the schema, built-ins like required, min, enum and match, plus custom sync or async functions. They run before save() and create(), all at once, and a failure rejects with a ValidationError listing each failing path, so nothing reaches the database. Update queries like updateOne and findOneAndUpdate skip validation unless you pass runValidators: true or set it globally, and even then validators that use this behave differently because this is the query. Since it's app-side only, I'd add MongoDB's $jsonSchema collection validation for invariants other clients must respect, and unique indexes for uniqueness, because Mongoose's unique option is an index, not a validator.

Open in topic →

populate vs $lookup?

Show answer

populate is a Mongoose feature that runs extra queries from the app: one $in query per populated path, then stitches the documents together in memory. It's convenient, works with Mongoose documents and models, and can populate across databases, but it's several round trips and can't filter or sort the parent by the referenced data. $lookup is a server-side aggregation stage: a left outer join done in one round trip, which can then $match, $group and $sort on the joined fields. For API responses that show an order with its customer, populate is fine; for reports or filtering on joined fields, use $lookup. If you populate the same data on every read, it's a sign the data should probably be embedded or partly denormalised.

Open in topic →

How do you make Mongoose queries faster?

Show answer

First the database side: the right indexes, checked with explain, and projections so the server sends only the fields you need. Then the Mongoose side: .lean() on read-only queries, which skips hydrating documents, so roughly half the CPU and memory in my measurement, cursors or stream() instead of loading huge result sets, populate with field selection or $lookup instead of per-document queries, and bulkWrite or insertMany for batches instead of saving documents in a loop. In production I'd also turn off autoIndex and build indexes in deployments, and reuse one connection with a sized pool.

Open in topic →

How do you use transactions from Node?

Show answer

With the driver I start a session and call session.withTransaction(async () => { … }), passing { session } to every operation inside, with majority write concern and snapshot read concern. The helper commits for me, retries the whole callback on TransientTransactionError such as write conflicts or failovers, with backoff, up to a 120-second limit, and retries the commit on UnknownTransactionCommitResult. So the callback must be idempotent and contain only database work. I end the session in finally. With Mongoose it's connection.transaction(fn), and with transactionAsyncLocalStorage enabled the session is passed automatically. And I keep transactions short and rare, because a single-document update or a conditional update usually does the job.

Open in topic →

Spot the bug

This checkout handler sometimes charges customers twice. Why?

JavaScript
await session.withTransaction(async () => {
  await orders.insertOne({ _id: orderId, total }, { session });
  await payments.charge(customer.card, total);          // calls the payment provider's API
  await products.updateOne({ _id: productId, stock: { $gte: 1 } }, { $inc: { stock: -1 } }, { session });
});
Show answer

The payment call is inside the transaction callback, and withTransaction re-runs the whole callback on a TransientTransactionError.

What’s happening
  1. Under load, the updateOne on a popular product hits a write conflict with another checkout, and the server aborts the transaction with TransientTransactionError.
  2. The database side is clean: the aborted order insert is rolled back.
  3. But payments.charge already ran, and the payment provider isn't part of the MongoDB transaction, so it isn't rolled back.
  4. withTransaction runs the callback again from the top, inserting the order again and charging the card again. With several conflicts, several charges.
  5. Simulated with a stub payments.charge that counts calls, while another checkout held the product for 100 ms: the result was { charges: 6, orders: 1, stock: 3 }. One order, one stock decrement, six charges.
  6. Fix: keep only database work in the callback. Reserve the stock and create the order with status: "pending" in the transaction, charge the card afterwards with an idempotency key, then mark the order paid. Never put side effects in code that may be retried.
Open in topic →

Redis is single-threaded — how is it so fast?

Show answer

"Redis keeps everything in memory and executes commands on one thread, one at a time. That sounds limiting, but most commands are O(1) or O(log n) and take about a microsecond, there's no query planner and no locking, and the network side is an event loop like Node's. Single-threading is also a feature: every command is atomic, so INCR or SET NX can't race. The real bottleneck is round trips, so you pipeline, and you avoid commands that scan large data — KEYS, big SMEMBERS, long Lua — because they block every client. Redis 6 added I/O threads for socket work, but command execution is still single-threaded; to scale writes you shard with Redis Cluster."

Open in topic →

Predict the order

redis-cli
> ZADD ch25:q:scores 2 "ThinkBook 14" 2 "Noise-cancelling Headphones" 2 "MacBook Air" 7 "USB-C Charger"
(integer) 4
> ZRANGE ch25:q:scores 0 -1
> ZRANGE ch25:q:scores 0 -1 REV

What do the two ZRANGEs print?

Show answer
Result
> ZRANGE ch25:q:scores 0 -1
1) "MacBook Air"
2) "Noise-cancelling Headphones"
3) "ThinkBook 14"
4) "USB-C Charger"
> ZRANGE ch25:q:scores 0 -1 REV
1) "USB-C Charger"
2) "ThinkBook 14"
3) "Noise-cancelling Headphones"
4) "MacBook Air"
What’s happening
  1. Sorted sets order by score first: the three products with score 2 come before USB-C Charger with 7.
  2. Members with the same score are ordered lexicographically by their bytes: M < N < T, so MacBook Air, Noise-cancelling Headphones, ThinkBook 14.
  3. REV reverses the whole ordering, ties included: highest score first, and among equal scores reverse byte order — ThinkBook 14 before Noise-cancelling Headphones before MacBook Air.
  4. So a leaderboard with ties is deterministic but alphabetical, which is rarely what you want. If ties should go to whoever got there first, fold time into the score (for example score = points × 10¹⁰ + (MAX_TS − ts)) or keep a separate tiebreaker.
Open in topic →

Which Redis data structure would you use for a leaderboard, and why?

Show answer

"A sorted set. Each player is a member and the score is their points; ZINCRBY updates a score atomically, ZRANGE key 0 9 REV WITHSCORES gives the top ten, and ZREVRANK gives one player's position — all O(log n), because Redis keeps the set ordered as you write. Ties are broken alphabetically, so if earlier should win I encode a timestamp into the score. For time windows, like weekly leaderboards, I'd use one key per week with an expiry, and ZUNIONSTORE to combine weeks."

Open in topic →

Does the TTL survive?

redis-cli
> SET ch25:q:session abc EX 100
> APPEND ch25:q:session def
> TTL ch25:q:session
> INCR ch25:q:counter
> EXPIRE ch25:q:counter 100
> SET ch25:q:counter 5
> TTL ch25:q:counter

What do the two TTLs return?

Show answer
Result
> SET ch25:q:session abc EX 100
OK
> APPEND ch25:q:session def
(integer) 6
> TTL ch25:q:session
(integer) 100
> INCR ch25:q:counter
(integer) 1
> EXPIRE ch25:q:counter 100
(integer) 1
> SET ch25:q:counter 5
OK
> TTL ch25:q:counter
(integer) -1
What’s happening
  1. APPEND modifies the existing string in place (abc → abcdef, length 6), so the session keeps its TTL: 100.
  2. The counter gets a 100-second TTL, then SET ch25:q:counter 5 replaces the value. Replacing a value discards the old TTL, so the counter now lives forever: -1.
  3. Rule of thumb: commands that alter a value (APPEND, INCR, HSET, LPUSH, SADD) keep the TTL; commands that overwrite it (SET, GETSET, RENAME onto it, *STORE) reset it. Use SET … KEEPTTL or SET … EX when overwriting.
Open in topic →

What's the difference between expiry and eviction in Redis?

Show answer

"Expiry is per key and deliberate: I set a TTL with SET … EX and Redis removes the key when it's due — lazily when someone reads it, and actively with a background cycle that samples keys with TTLs. Eviction is server-wide and only happens when memory hits maxmemory: Redis removes keys according to maxmemory-policy. The default is noeviction, which rejects writes with an OOM error; for a cache I'd use allkeys-lru, or allkeys-lfu if popularity is stable. Redis's LRU and LFU are approximations based on sampling — maxmemory-samples trades CPU for accuracy. And I wouldn't put sessions or rate-limit counters in an instance with an allkeys policy, because eviction doesn't care that they matter."

Open in topic →

Explain cache-aside versus write-through versus write-behind.

Show answer

"In cache-aside the application owns the cache: on a read it checks Redis, on a miss it reads the database and fills Redis with a TTL; on a write it updates the database and deletes the key. It's simple and only caches what's read, but data can be stale for up to the TTL and there are races on fill. Write-through writes the database and the cache together on every write, so reads right after a write hit fresh data, at the cost of slower writes and caching things nobody reads. Write-behind writes to Redis first and flushes to the database in batches — great for counters or metrics with huge write rates, but anything not flushed is lost if Redis dies, so I'd only use it where losing a few seconds is acceptable. In all three the database stays the source of truth, and a TTL is the safety net."

Open in topic →

How would you keep a Redis cache consistent with MySQL?

Show answer

"I treat MySQL as the source of truth and accept bounded staleness: every cache entry has a TTL. On writes I commit to MySQL first, then delete the cache key. That still has a race — a reader that read the old row before my write can refill the cache after my delete — so for data where it matters I version the rows and write the cache with a Lua script that refuses to overwrite a newer version. For many services or many writers, I'd invalidate from the binlog with change data capture, so any write path — even a manual SQL fix — invalidates the cache. For hot keys I protect against stampedes with a short SET NX PX lock or by serving stale while one instance refreshes."

Open in topic →

How would you implement a distributed rate limiter?

Show answer

"In Redis, so every app instance shares one counter per client. The simplest is a fixed window: INCR the client's key and set EXPIRE … NX in the same MULTI, reject when the count passes the limit. The TTL resets the window and cleans up idle clients. It allows double bursts at window edges, so for logins I'd use a sliding log — a sorted set of timestamps trimmed with ZREMRANGEBYSCORE — and for APIs a token bucket. Both need several steps per check, so they go in a Lua script for atomicity and use Redis's TIME so app clocks don't matter. I'd keep those keys away from eviction and decide whether to fail open or closed when Redis is down."

Open in topic →

How do you implement a distributed lock with Redis, and what are its limits?

Show answer

"SET lock:<resource> <unique token> NX PX <ttl>: it only succeeds if the key doesn't exist, and the expiry stops a crashed holder from blocking everyone. To release, I compare-and-delete — a Lua script, or DELEX … IFEQ on Redis 8.4 — so I never delete a lock someone else now holds. The limit is that it's a lease: if my process pauses longer than the TTL, the lock expires and someone else gets it while I still think I hold it. A safe release doesn't fix that. If correctness matters, I use fencing tokens — an increasing number from INCR that the database checks on every write — or a database lock. Redlock spreads the lock over several primaries for availability, but it still depends on timing assumptions."

Open in topic →

When would you use Redis Pub/Sub, Streams or a real message broker?

Show answer

"Pub/Sub is fire-and-forget: a message goes to whoever is subscribed at that moment and isn't stored, so a disconnected subscriber misses it. I'd use it for cache-invalidation broadcasts or live notifications where a miss is harmless. Streams are a persistent log: entries have ids, consumers can replay, and consumer groups split work with acknowledgements, a pending list and XAUTOCLAIM for crashed workers — at-least-once delivery, so handlers must be idempotent. That covers job queues and moderate event feeds. When I need long retention on disk, very high throughput, partitions with ordering guarantees and replay of weeks of history across many teams, I'd move to Kafka; and for complex routing, RabbitMQ."

Open in topic →

RDB versus AOF — which would you use?

Show answer

"RDB is a point-in-time snapshot written by a forked child: compact, fast to restart from and ideal for backups, but a crash loses everything since the last snapshot, usually minutes. AOF logs every write and fsyncs every second by default, so a crash loses about a second; it's bigger and slower to replay, and Redis rewrites it in the background — since 7.0 as a base snapshot plus incremental files. For a pure cache I'd turn both off or keep just RDB so restarts are warm. For anything I'd mind losing I'd enable AOF with everysec and keep RDB snapshots for backups, which is what the Redis docs recommend. And with persistence off, I'd never let a primary auto-restart, because it comes back empty and its replicas copy the empty dataset."

Open in topic →

What happened with the Redis licence, and what is Valkey?

Show answer

"Redis was BSD until 7.2. In March 2024 Redis Inc moved Redis 7.4 onwards to a dual RSALv2/SSPLv1 licence — source-available, not open source — mainly to stop cloud providers selling Redis as a service without a deal. Days later the Linux Foundation forked Redis 7.2.4 as Valkey, under BSD, with AWS, Google and others behind it, and AWS ElastiCache now offers Valkey at a lower price. In May 2025 Redis 8 added AGPLv3 as a third option, so it's OSI open source again, and merged the old Redis Stack modules into the core. For an application using Redis as a cache or queue, none of these licences restrict you; the choice between Redis 8 and Valkey comes down to features you need, the managed offering you use and your company's licence policy."

Open in topic →

SQL or NoSQL — how do you decide?

Show answer

"I start from the data and the access patterns, not the label. If the data is highly relational, has to stay consistent across entities — orders, payments, inventory — and I can't predict every query, I default to a relational database: the schema protects the data, joins answer new questions, and multi-row transactions are the norm. If the data is naturally an aggregate that's read and written as a whole, its shape varies, and the access patterns are known — a product catalogue, user profiles, event payloads — a document store fits well and shards easily. Joins on indexed keys aren't slow, so performance alone rarely decides it. And plenty of systems use both."

Open in topic →

Explain the CAP theorem. Is MongoDB CP or AP?

Show answer

"CAP says that when a network partition splits a replicated system, each side must choose between staying available — answering, possibly with stale data — and staying consistent — refusing until it can coordinate. Partitions aren't optional, so it's really C versus A during a partition. PACELC adds that even without a partition you trade latency for consistency, because waiting for replicas is slow. MongoDB is usually described as CP: in a partition the minority side has no primary and stops taking writes, and with w: majority and majority reads you don't see rolled-back data. But it's configurable — reading from secondaries or using w: 1 moves it towards AP. Most real databases are tunable, so I'd describe the settings, not the label."

Open in topic →

Which guarantee broke?

A user changes their display name and the confirmation page shows the new name. They refresh, and the old name is back. A minute later it's new again. Which consistency guarantee was violated, and what's the cheapest fix?

Show answer

Monotonic reads (and, on the refresh, read-your-writes).

What’s happening
  1. The confirmation page was probably rendered from the primary, or from the write's own response, so the user saw the new name.
  2. The refresh went to a lagging replica that hadn't applied the update, so the user saw an older state than one they'd already seen — time went backwards. That's a monotonic-reads violation; since it's their own write, read-your-writes is broken too.
  3. A minute later the replica caught up — eventual consistency did its job, just not in a way the user can tolerate.
  4. Cheapest fixes: after a user writes, read their data from the primary for a short window (a cookie or session flag); or pin each user's session to one replica so reads never go backwards. Making the whole database strongly consistent would be far more expensive than either.
Open in topic →

What's the difference between strong and eventual consistency?

Show answer

"Strong consistency — linearizability — means the system behaves as if there's one copy: once a write is acknowledged, every later read anywhere sees it. You get it from a single primary, or from consensus systems like etcd or Spanner, and you pay in latency and availability during partitions. Eventual consistency only promises that if writes stop, the copies converge; in the meantime readers can see old data, and even see it go backwards. In between are causal consistency and session guarantees — read-your-writes and monotonic reads — which are what users actually notice. In practice I use replicas for scale but route a user's reads to the primary right after they write, or use MongoDB's causally consistent sessions."

Open in topic →

What's the difference between OLTP and OLAP, and why not run analytics on the production database?

Show answer

"OLTP is the application's workload: many small, concurrent transactions that read or write a few rows by key, where latency and correctness matter. OLAP is analytics: few queries that scan millions of rows but only a few columns, where throughput matters. Row stores like InnoDB are built for OLTP; column stores like ClickHouse, BigQuery or Snowflake store each column compressed and process it in vectorised batches, which is orders of magnitude better for scans. Running heavy reports on the production primary steals CPU, I/O and buffer pool from the transactions customers are waiting on, so I'd move them to a replica at minimum, and to a warehouse fed by CDC or ELT when the data grows."

Open in topic →

When would you choose a graph database or a wide-column store?

Show answer

"A graph database when the core queries are about relationships several hops deep with filters along the way — recommendation, fraud rings, access-control graphs — because it follows stored pointers instead of building large join results; for one or two hops, like an org chart, a recursive CTE is fine. A wide-column store like Cassandra when I need very high write throughput across many nodes and regions, and my reads are always by a known partition key — time-ordered events per device or per user. I design its tables per query, and give up joins and ad-hoc queries."

Open in topic →

What is polyglot persistence, and what are the risks?

Show answer

"Using different databases for different parts of a system — say MySQL for orders, Redis for sessions and caching, Elasticsearch for product search and a warehouse for analytics — because each is best at its job. The risks are operational cost, since every store needs backups, monitoring and expertise, and consistency between stores. I keep one source of truth per piece of data and treat everything else as derived: changes flow out of the primary database through a transactional outbox or change data capture, consumers are idempotent, and derived stores can be rebuilt. I avoid dual writes from request handlers, because a failure between the two writes leaves the stores silently out of sync."

Open in topic →

Pick a database: a ride-hailing app

A ride-hailing app needs: driver locations updated every 4 seconds and queried by "drivers within 2 km"; trips and payments that must never be lost or double-charged; and a weekly report of revenue per city. What would you use for each part?

Show answer

Three workloads, three answers — with one source of truth.

What’s happening
  1. Driver locations: very high write rate, only the latest position matters, losing one update is harmless, and the query is "near me". Redis geo commands fit (GEOADD to update, GEOSEARCH … BYRADIUS 2 km), as shown in Data structures. It's not the source of truth for anything.
  2. Trips and payments: correctness matters most — a trip, its fare and the payment must change together, and charges must be idempotent. A relational database with transactions and unique constraints (an idempotency key on payments) is the natural fit.
  3. Weekly revenue per city: an aggregate over all trips. Run it on a replica at first; move it to a warehouse fed by CDC when the trip table gets large, so it never competes with live trips.
  4. The interview point is the reasoning: separate the workloads by their access pattern and consistency needs, keep one source of truth, and treat the others as derived or ephemeral.
Open in topic →

Pick a database: a product catalogue with very different products

An online shop sells laptops (CPU, RAM, screen size), books (author, ISBN, pages) and clothes (size, colour, material). Product pages are read 1,000 times more often than they're edited, and customers search and filter by those attributes. MySQL, MongoDB, or something else?

Show answer

Either can work; the attributes and the search are what decide it.

What’s happening
  1. The attributes vary by category, which is awkward as fixed relational columns. Options in MySQL: a JSON column for the attributes (with generated columns and indexes on the ones you filter by), or an entity-attribute-value table, which is flexible but painful to query.
  2. MongoDB fits the shape naturally: each product document has the attributes it needs, and indexes (including wildcard indexes) cover filtering. Reads of a whole product are one document.
  3. Faceted search with relevance ("laptops, 16 GB, under $1,000, sorted by best match") is really a search-engine job: a search index built from the catalogue, whether the source of truth is MySQL or MongoDB.
  4. A defensible answer: keep products and their attributes wherever the rest of the shop's data lives if it's relational (orders must reference products reliably), store variable attributes as JSON, cache product pages in Redis, and feed a search index for search. Choosing MongoDB for the catalogue is also defensible, if you accept two databases.
Open in topic →

Spot the bad reason

Which of these is a weak reason for choosing MongoDB over PostgreSQL? (a) Documents vary a lot in shape. (b) "Joins are slow." (c) We need built-in sharding for a dataset that will outgrow one machine. (d) The team already runs MongoDB well.

Show answer

(b). Joins on indexed keys are cheap.

What’s happening
  1. (a) is a real reason: a flexible document model fits genuinely variable data better than a fixed schema.
  2. (b) is the weak one: in SQL vs NoSQL: the real trade-offs a four-table join by primary key took about 111 µs against 140 µs for one document read. Joins become expensive across shards or on unindexed columns — which is an argument about (c), not about joins in general.
  3. (c) is a real reason: MongoDB shards natively, while PostgreSQL needs Citus or application-level sharding.
  4. (d) is a real reason too: operational experience is a large part of running a database well.
Open in topic →

How would you choose a database for a new service?

Show answer

"I'd start with the data and how it's accessed: is it relational with lots of cross-entity queries, or self-contained aggregates; are reads by key, by search, by time range or big scans; what are the read and write volumes and how fast will they grow. Then consistency: does it involve money or inventory where I need transactions and strong consistency, or can it tolerate staleness. Then operations: what the team can run well and whether a managed service exists. My default is a relational database as the source of truth with Redis for caching and ephemeral state, and I add a search engine, a warehouse or a specialised store when a concrete requirement shows up — feeding them from the primary through an outbox or CDC, rather than dual writes."

Open in topic →

Why does WHERE annual > 1500000 fail when annual is defined in the SELECT?

SQL
SELECT name, salary * 12 AS annual
FROM employees
WHERE annual > 1500000;
Show answer

Because WHERE is evaluated before SELECT, so the alias doesn't exist yet. MySQL says so:

Result
ERROR 1054 (42S22): Unknown column 'annual' in 'where clause'

Repeat the expression (WHERE salary * 12 > 1500000), or filter in an outer query. MySQL also lets you use the alias in HAVING, which runs after SELECT:

SQL
SELECT name, salary * 12 AS annual
FROM employees
HAVING annual > 1500000
ORDER BY annual DESC;
Result
+-------+------------+
| name  | annual     |
+-------+------------+
| Asha  | 2220000.00 |
| Ben   | 1704000.00 |
| Chloe | 1704000.00 |
| Elena | 1560000.00 |
+-------+------------+
What’s happening
  1. The logical order is FROM → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. The database can execute it differently, but the meaning follows this order.
  2. When WHERE runs, each row only has its table columns (name, salary, …). annual is created later, in SELECT, hence error 1054.
  3. ORDER BY runs after SELECT, so ORDER BY annual is fine in every database.
  4. HAVING without GROUP BY that refers to a SELECT alias is a MySQL extension: it treats the whole result as one group and allows the alias. PostgreSQL 18 rejects the same shape (tried on a small table e) with column "e.name" must appear in the GROUP BY clause or be used in an aggregate function. In portable SQL, wrap the query: SELECT * FROM (…) AS t WHERE annual > 1500000.
  5. The same rule explains why window functions can't appear in WHERE: they're computed in the SELECT step too.

Learn more: Logical query processing order.

Open in topic →

WHERE vs HAVING: which departments have at least three employees?

Write the query, and say why WHERE COUNT(*) >= 3 can't work.

Show answer

WHERE filters rows before grouping; HAVING filters groups after aggregation. An aggregate doesn't exist at WHERE time, so the condition belongs in HAVING:

SQL
SELECT department_id, COUNT(*) AS n
FROM employees
GROUP BY department_id
HAVING n >= 3
ORDER BY n DESC;
Result
+---------------+---+
| department_id | n |
+---------------+---+
|             1 | 4 |
|             2 | 3 |
+---------------+---+
What’s happening
  1. GROUP BY department_id forms groups: 1 (4 people), 2 (3), 3 (2) and NULL (Jonas).
  2. COUNT(*) is computed per group; HAVING n >= 3 then keeps Engineering and Sales.
  3. WHERE COUNT(*) >= 3 fails with ERROR 1111 (HY000): Invalid use of group function, because WHERE judges one row at a time, before any group exists.
  4. Put row-level conditions in WHERE whenever you can (WHERE hired_on >= '2020-01-01'): it removes rows before the grouping work, which is cheaper, and it can use indexes.
  5. HAVING n uses the alias — allowed in MySQL. The portable form is HAVING COUNT(*) >= 3.

Learn more: HAVING vs WHERE.

Open in topic →

Predict: COUNT(*), COUNT(city) and COUNT(DISTINCT city)

Customers' cities are Toronto, Mumbai, London, NULL, Toronto, Dubai.

SQL
SELECT COUNT(*), COUNT(city), COUNT(DISTINCT city) FROM customers;
Show answer

6, 5, 4.

Result
+----------+-------------+----------------------+
| COUNT(*) | COUNT(city) | COUNT(DISTINCT city) |
+----------+-------------+----------------------+
|        6 |           5 |                    4 |
+----------+-------------+----------------------+
What’s happening
  1. COUNT(*) counts rows, whatever they contain: 6.
  2. COUNT(city) counts non-NULL values. Sofia's city is NULL, so 5.
  3. COUNT(DISTINCT city) counts different non-NULL values: Toronto, Mumbai, London, Dubai — 4. Toronto appears twice but counts once, and NULL isn't a value to count.
  4. COUNT(1) is identical to COUNT(*) in MySQL; there's no performance difference, despite the folklore.
  5. Every other aggregate (SUM, AVG, MIN, MAX) ignores NULLs the same way — which is why AVG can silently change its denominator.

Learn more: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT).

Open in topic →

Where does a NULL city sort, and how do you move it to the end?

SQL
SELECT name, city FROM customers ORDER BY city;
Show answer

First. MySQL treats NULL as smaller than any value, so it comes first in ascending order and last in descending order:

Result
+-------+---------+
| name  | city    |
+-------+---------+
| Sofia | NULL    |
| Zara  | Dubai   |
| Liam  | London  |
| Maya  | Mumbai  |
| Rohit | Toronto |
| Noah  | Toronto |
+-------+---------+

To put NULLs last while keeping the ascending order, sort by a "is it null?" flag first:

SQL
SELECT name, city FROM customers ORDER BY city IS NULL, city;
Result
+-------+---------+
| name  | city    |
+-------+---------+
| Zara  | Dubai   |
| Liam  | London  |
| Maya  | Mumbai  |
| Rohit | Toronto |
| Noah  | Toronto |
| Sofia | NULL    |
+-------+---------+
What’s happening
  1. city IS NULL is 0 for real cities and 1 for Sofia, so sorting by it first puts all real cities before her.
  2. Within the 0 group, the second key city sorts alphabetically.
  3. MySQL has no NULLS FIRST / NULLS LAST syntax; PostgreSQL does, and its default is the opposite of MySQL's: on PostgreSQL 18, ORDER BY city put the NULL row last. Worth knowing when a query moves between them.
  4. Rohit and Noah tie on Toronto, and their relative order isn't guaranteed. Add a tiebreaker (, id) whenever the order matters, for example for pagination.

Learn more: Sorting with ORDER BY and MySQL vs PostgreSQL: SQL differences you'll hit first.

Open in topic →

Predict six MySQL expressions

SQL
SELECT 7 / 2 AS slash, 7 DIV 2 AS div_, 7 % 2 AS modulo,
       '10' < '9' AS str_cmp, 10 < 9 AS num_cmp, 1 / 0 AS div_zero;
Show answer

3.5000, 3, 1, 1, 0 and NULL (with a warning).

Result
+--------+------+--------+---------+---------+----------+
| slash  | div_ | modulo | str_cmp | num_cmp | div_zero |
+--------+------+--------+---------+---------+----------+
| 3.5000 |    3 |      1 |       1 |       0 |     NULL |
+--------+------+--------+---------+---------+----------+
What’s happening
  1. / is always decimal division in MySQL, even between integers: 3.5000 (four decimal places by default, from div_precision_increment). PostgreSQL 18 returns 3 for SELECT 7/2, because integer divided by integer stays an integer there.
  2. DIV is integer division (truncating): 3. % (or MOD) is the remainder: 1.
  3. '10' < '9' compares strings, character by character: '1' sorts before '9', so it's true (1). Numbers compare numerically: 10 < 9 is 0. This is why storing numbers in VARCHAR columns breaks sorting.
  4. 1 / 0 returns NULL in a SELECT, with Warning 1365 Division by 0. In an INSERT or UPDATE under the default strict mode (which includes ERROR_FOR_DIVISION_BY_ZERO), it's an error instead.
  5. Booleans print as 1 and 0 because MySQL's BOOLEAN is just TINYINT(1).

Learn more: String, number and date functions.

Open in topic →

Predict: does 'abc' equal 'abc ' (with trailing spaces)?

SQL
SELECT 'abc' = 'abc   ' AS no_pad,
       'abc' = 'abc   ' COLLATE utf8mb4_general_ci AS pad_space;
Show answer

It depends on the collation: 0 with MySQL 8.0+'s default utf8mb4_0900_ai_ci, but 1 with utf8mb4_general_ci, the utf8mb4 default on MySQL 5.7.

Result
+--------+-----------+
| no_pad | pad_space |
+--------+-----------+
|      0 |         1 |
+--------+-----------+
What’s happening
  1. Every collation has a pad attribute. information_schema.COLLATIONS shows utf8mb4_0900_ai_ci as NO PAD and utf8mb4_general_ci as PAD SPACE.
  2. PAD SPACE collations compare as if the shorter string were padded with spaces, so trailing spaces are ignored and the strings are equal.
  3. NO PAD collations compare the actual characters, so 'abc ' is longer and different.
  4. Upgrading from 5.7 to 8.0 and switching to the new default collation can therefore change query results and even make a unique index accept 'abc' and 'abc ' as two values. It's an "old and new" trap worth naming.
  5. Both are case-insensitive (_ci), so 'abc' = 'ABC' is 1 either way. Use a _bin or _cs collation for case-sensitive comparison.

Learn more: Strings: CHAR, VARCHAR, TEXT and character sets.

Open in topic →

Spot the bug: BETWEEN on a DATETIME column misses an order

Orders 1 and 3 were placed on 1 February and 10 February 2025. Why does this return only order 1?

SQL
SELECT id, ordered_at FROM orders
WHERE ordered_at BETWEEN '2025-02-01' AND '2025-02-10'
ORDER BY ordered_at;
Show answer

'2025-02-10' compared with a DATETIME means midnight at the start of 10 February. Order 3 was placed at 09:20 that day, after the upper bound:

Result
+----+---------------------+
| id | ordered_at          |
+----+---------------------+
|  1 | 2025-02-01 10:00:00 |
+----+---------------------+

Use a half-open range instead:

SQL
SELECT id, ordered_at FROM orders
WHERE ordered_at >= '2025-02-01' AND ordered_at < '2025-02-11'
ORDER BY ordered_at;
Result
+----+---------------------+
| id | ordered_at          |
+----+---------------------+
|  1 | 2025-02-01 10:00:00 |
|  3 | 2025-02-10 09:20:00 |
+----+---------------------+
What’s happening
  1. BETWEEN a AND b is inclusive at both ends: >= a AND <= b. That's fine for integers and DATE columns.
  2. For DATETIME, the string '2025-02-10' is converted to 2025-02-10 00:00:00. Anything later that day is > b.
  3. >= start AND < next day includes the whole last day at any precision, including fractional seconds, and it can still use an index on ordered_at.
  4. Writing DATE(ordered_at) BETWEEN … also gives the right rows, but wrapping the column in a function prevents a normal index from being used.

Learn more: Dates and times: DATETIME vs TIMESTAMP and Filtering with WHERE.

Open in topic →

Predict the row counts: customers JOIN orders vs LEFT JOIN, and UNION vs UNION ALL

There are 6 customers and 8 orders; Zara has no orders. Predict all four numbers.

SQL
SELECT
  (SELECT COUNT(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id) AS left_rows,
  (SELECT COUNT(*) FROM customers c JOIN orders o ON o.customer_id = c.id)      AS inner_rows;

SELECT
  (SELECT COUNT(*) FROM (SELECT city FROM customers UNION     SELECT city FROM customers) u) AS union_rows,
  (SELECT COUNT(*) FROM (SELECT city FROM customers UNION ALL SELECT city FROM customers) u) AS union_all_rows;
Show answer

9 and 8; 5 and 12.

Result
+-----------+------------+
| left_rows | inner_rows |
+-----------+------------+
|         9 |          8 |
+-----------+------------+

+------------+----------------+
| union_rows | union_all_rows |
+------------+----------------+
|          5 |             12 |
+------------+----------------+
What’s happening
  1. The inner join returns one row per matching pair. Every order has exactly one customer, so there are 8 pairs.
  2. The LEFT JOIN returns those 8 plus one NULL-padded row for each customer with no match — Zara — so 9. A join's row count is driven by matches, not by the size of the left table.
  3. UNION ALL simply appends: 6 + 6 = 12 rows.
  4. UNION removes duplicate rows from the combined result: the distinct cities are Toronto, Mumbai, London, Dubai and NULL — 5. Unlike =, UNION treats two NULLs as duplicates.
  5. UNION costs a de-duplication step (a temporary table or sort). Use UNION ALL unless you need duplicates removed.

Learn more: LEFT and RIGHT OUTER JOIN and Set operations: UNION, INTERSECT and EXCEPT.

Open in topic →

Predict: a CASE with no ELSE

SQL
SELECT name,
       CASE WHEN stock = 0  THEN 'sold out'
            WHEN stock < 10 THEN 'low' END AS stock_flag
FROM products ORDER BY id;
Show answer

Products that match neither branch get NULL — a CASE without ELSE defaults to ELSE NULL.

Result
+---------------------------------------+------------+
| name                                  | stock_flag |
+---------------------------------------+------------+
| ThinkBook 14                          | NULL       |
| MacBook Air                           | low        |
| Pixel 10                              | NULL       |
| iPhone 17                             | sold out   |
| SQL Performance Explained             | NULL       |
| Designing Data-Intensive Applications | NULL       |
| USB-C Charger                         | NULL       |
| Noise-cancelling Headphones           | low        |
+---------------------------------------+------------+
What’s happening
  1. CASE tests the WHENs in order and stops at the first true one. The iPhone (stock 0) matches the first branch, so it's "sold out", not "low", even though 0 < 10 is also true.
  2. The MacBook (5) and headphones (8) match the second branch.
  3. Everything else matches nothing and falls to the implicit ELSE NULL.
  4. This matters inside aggregates: SUM(CASE WHEN … THEN 1 END) returns NULL for a group where nothing matched, while SUM(CASE WHEN … THEN 1 ELSE 0 END) returns 0.

Learn more: CASE expressions.

Open in topic →

How many rows does COUNT() OVER () return, compared with COUNT()?

Sales has three employees.

SQL
SELECT name, COUNT(*) OVER () AS total, salary
FROM employees
WHERE department_id = 2;
Show answer

Three rows, each with total = 3. A window function adds a value to every row; an aggregate without OVER collapses the rows into one.

Result
+-------+-------+-----------+
| name  | total | salary    |
+-------+-------+-----------+
| Elena |     3 | 130000.00 |
| Farid |     3 |  95000.00 |
| Grace |     3 |  99000.00 |
+-------+-------+-----------+
What’s happening
  1. WHERE department_id = 2 runs first and leaves three rows.
  2. COUNT(*) OVER () uses an empty window — all rows of the result — so each row gets the count of the whole result: 3.
  3. SELECT name, COUNT(*) FROM … WHERE department_id = 2 without OVER would collapse to one row, and under ONLY_FULL_GROUP_BY it's rejected because name isn't grouped.
  4. That's the interview line: "GROUP BY reduces rows; window functions keep every row and add a computed column." It's why window functions are the tool for running totals, ranks and percent-of-total.

Learn more: Window functions: OVER and PARTITION BY.

Open in topic →

DELETE vs TRUNCATE inside a transaction — predict the counts and the next id

The table t_del has three rows with ids 1–3.

Starting dataThe t_del table
SQL
DROP TABLE IF EXISTS t_del;
CREATE TABLE t_del (id INT AUTO_INCREMENT PRIMARY KEY, v INT);
INSERT INTO t_del (v) VALUES (1),(2),(3);
SQL
START TRANSACTION; DELETE FROM t_del;   ROLLBACK;
SELECT COUNT(*) AS after_delete_rollback FROM t_del;

START TRANSACTION; TRUNCATE TABLE t_del; ROLLBACK;
SELECT COUNT(*) AS after_truncate_rollback FROM t_del;

INSERT INTO t_del (v) VALUES (9);
SELECT * FROM t_del;
Show answer

3, then 0, then the new row gets id 1. DELETE is a normal, transactional row operation; TRUNCATE is DDL that commits implicitly, can't be rolled back and resets AUTO_INCREMENT.

Result
+-----------------------+
| after_delete_rollback |
+-----------------------+
|                     3 |
+-----------------------+

+-------------------------+
| after_truncate_rollback |
+-------------------------+
|                       0 |
+-------------------------+

+----+------+
| id | v    |
+----+------+
|  1 |    9 |
+----+------+
What’s happening
  1. DELETE FROM t_del removes rows one by one inside the transaction, writing undo records. ROLLBACK uses them to restore all three rows.
  2. TRUNCATE TABLE drops and recreates the table internally. It causes an implicit commit (of the transaction it's in and of itself), so the ROLLBACK afterwards has nothing to undo: the table stays empty.
  3. Because the table was recreated, the AUTO_INCREMENT counter starts again, so the next insert gets id 1. After a DELETE, it would have been 4.
  4. Other differences: TRUNCATE doesn't fire DELETE triggers and fails if another table's foreign key references this one. DROP TABLE removes the table itself, structure and all.
  5. Use DELETE when you need a WHERE, triggers or the ability to roll back; TRUNCATE to empty a large table fast.

Learn more: DELETE vs TRUNCATE vs DROP and Autocommit and implicit commits.

Open in topic →

Which normal form does this table break, and why is unit_price allowed to stay?

order_items (order_id, product_id) is the primary key
order_id | product_id | quantity | unit_price | product_name
Show answer

product_name breaks second normal form (2NF): it depends on only part of the composite key, product_id, not on the whole (order_id, product_id). Move it to products. unit_price stays, because it isn't the product's current price — it's the price on that order, a fact about the order line.

What’s happening
  1. 1NF: every column holds a single value, and rows are identified by a key. This table passes.
  2. 2NF: every non-key column must depend on the whole key. quantity depends on both (how many of this product on this order). product_name depends only on product_id, so it's a partial dependency.
  3. The cost of the violation is update anomalies: rename a product and you must update every order line that mentions it, or the names disagree.
  4. 3NF additionally forbids non-key columns depending on other non-key columns (a transitive dependency), like storing customer_city on orders next to customer_id.
  5. unit_price looks like a copy of products.price, but it records history: when the price changes, past orders must keep the price the customer paid. Saying "this is deliberate denormalisation of a point-in-time value" is the senior answer.

Learn more: First, second and third normal form and Why normalise: update, insert and delete anomalies.

Open in topic →

Which of these WHERE clauses can use the index (customer_id, status, ordered_at), and how much of it?

  1. WHERE customer_id = 42 AND ordered_at >= '2025-01-01'
  2. WHERE customer_id = 42 AND status = 'shipped' AND ordered_at >= '2025-01-01'
  3. WHERE status = 'shipped'
Show answer

(1) uses only the first column, (2) uses all three, (3) can't use it at all. It's the leftmost-prefix rule: a B+tree on (a, b, c) is sorted by a, then b within a, then c within b, so it can only be searched from the left.

SQL
EXPLAIN FORMAT=TRADITIONAL SELECT * FROM big_orders
WHERE customer_id = 42 AND ordered_at >= '2025-01-01';

EXPLAIN FORMAT=TRADITIONAL SELECT * FROM big_orders
WHERE customer_id = 42 AND status = 'shipped' AND ordered_at >= '2025-01-01';

EXPLAIN FORMAT=TRADITIONAL SELECT * FROM big_orders
WHERE status = 'shipped';
Result
+----+-------------+------------+------------+------+-------------------------------+----------------------+---------+-------+------+----------+-----------------------+
| id | select_type | table      | partitions | type | possible_keys                 | key                  | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+------------+------------+------+-------------------------------+----------------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | big_orders | NULL       | ref  | idx_cust_status_date,idx_date | idx_cust_status_date | 4       | const |   25 |    50.00 | Using index condition |
+----+-------------+------------+------------+------+-------------------------------+----------------------+---------+-------+------+----------+-----------------------+

+----+-------------+------------+------------+-------+-------------------------------+----------------------+---------+------+------+----------+-----------------------+
| id | select_type | table      | partitions | type  | possible_keys                 | key                  | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+------------+------------+-------+-------------------------------+----------------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | big_orders | NULL       | range | idx_cust_status_date,idx_date | idx_cust_status_date | 51      | NULL |    1 |   100.00 | Using index condition |
+----+-------------+------------+------------+-------+-------------------------------+----------------------+---------+------+------+----------+-----------------------+

+----+-------------+------------+------------+------+---------------+------+---------+------+-------+----------+-------------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref  | rows  | filtered | Extra       |
+----+-------------+------------+------------+------+---------------+------+---------+------+-------+----------+-------------+
|  1 | SIMPLE      | big_orders | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 50045 |    10.00 | Using where |
+----+-------------+------------+------------+------+---------------+------+---------+------+-------+----------+-------------+
What’s happening
  1. key_len is the number of index bytes used for searching. customer_id INT is 4 bytes; status VARCHAR(10) in utf8mb4 is 10 × 4 + 2 = 42; DATETIME is 5. So 4 means "customer_id only" and 51 means all three columns.
  2. Query 1 skips status, so the index can only seek to customer_id = 42 (25 rows). ordered_at sits behind status in the sort order, so it can't narrow the search; MySQL checks it on each index entry instead — that's what "Using index condition" (index condition pushdown) means.
  3. Query 2 has equality on the first two columns and a range on the third, so the whole index narrows the search to an exact slice.
  4. Query 3 has no condition on customer_id, so the index is useless for searching: possible_keys is NULL and the plan is a full table scan (ALL) over about 50,000 rows.
  5. The design rule that follows: put equality columns first and the range column last, and order the columns to match your most important queries. (MySQL 8.0.13+ can sometimes "skip scan" a missing leading column with few distinct values, but don't design around it.)

Learn more: Composite indexes and the leftmost-prefix rule and Reading EXPLAIN.

Open in topic →

What does "covering index" mean, and which of these two queries is covered?

SQL
EXPLAIN SELECT customer_id, status, ordered_at FROM big_orders
WHERE customer_id = 42 AND status = 'paid'\G

EXPLAIN SELECT customer_id, status, ordered_at, total FROM big_orders
WHERE customer_id = 42 AND status = 'paid'\G
Show answer

An index covers a query when every column the query needs is in the index, so MySQL never has to read the table row. The first query is covered; adding total breaks it.

Result
*************************** 1. row ***************************
EXPLAIN: -> Covering index lookup on big_orders using idx_cust_status_date (customer_id = 42, status = 'paid')  (cost=0.35 rows=1)

*************************** 1. row ***************************
EXPLAIN: -> Index lookup on big_orders using idx_cust_status_date (customer_id = 42, status = 'paid')  (cost=0.35 rows=1)
What’s happening
  1. The first query selects only customer_id, status and ordered_at — all three are in idx_cust_status_date. The tree plan says Covering index lookup; in the traditional format the same query shows Extra: Using index.
  2. total isn't in the index. For the second query MySQL finds matching entries in the index, then must fetch each row from the clustered index to read total: a plain "Index lookup".
  3. In InnoDB, every secondary index entry also stores the row's primary key, because that's how it finds the row. So SELECT id, customer_id FROM … WHERE customer_id = 42 is covered too, even though id isn't listed in the index definition.
  4. The extra lookup is cheap for one row but adds a random read per row; for a query that touches thousands of rows, covering can be the difference between milliseconds and seconds.
  5. The trade-off: wider indexes cost disk, memory and slower writes. Add columns to an index for your hottest queries, not for every query.

Learn more: Covering indexes and Clustered and secondary indexes in InnoDB.

Open in topic →

Why does WHERE YEAR(ordered_at) = 2024 AND MONTH(ordered_at) = 3 ignore idx_date?

SQL
EXPLAIN SELECT * FROM big_orders
WHERE YEAR(ordered_at) = 2024 AND MONTH(ordered_at) = 3\G
Show answer

Because the indexed column is wrapped in a function. The index is sorted by ordered_at, not by YEAR(ordered_at), so MySQL can't search it and scans the whole table:

Result
*************************** 1. row ***************************
EXPLAIN: -> Filter: ((year(big_orders.ordered_at) = 2024) and (month(big_orders.ordered_at) = 3))  (cost=5061 rows=50045)
    -> Table scan on big_orders  (cost=5061 rows=50045)

Rewrite the condition as a range on the bare column:

SQL
EXPLAIN SELECT * FROM big_orders
WHERE ordered_at >= '2024-03-01' AND ordered_at < '2024-04-01'\G
Result
*************************** 1. row ***************************
EXPLAIN: -> Index range scan on big_orders using idx_date over ('2024-03-01 00:00:00' <= ordered_at < '2024-04-01 00:00:00'), with index condition: ((big_orders.ordered_at >= TIMESTAMP'2024-03-01 00:00:00') and (big_orders.ordered_at < TIMESTAMP'2024-04-01 00:00:00'))  (cost=543 rows=1207)
What’s happening
  1. The tree is read from the innermost line out: a table scan of about 50,000 rows feeds a filter that evaluates YEAR() and MONTH() on every row.
  2. The rewritten query is the same set of rows, expressed so the optimizer can seek: an index range scan estimated at 1,207 rows, with a cost about a tenth of the scan's (543 vs 5,061).
  3. "Sargable" is the jargon: a predicate is sargable when the column stands alone on one side of the comparison. col + 1 = 5, LOWER(col) = 'x' and DATE(col) = '…' are not.
  4. If you really need to filter by an expression, MySQL 8.0.13+ supports functional indexes, e.g. CREATE INDEX idx_year ON big_orders ((YEAR(ordered_at))), and the optimizer uses it when the query uses the identical expression.

Learn more: Why an index isn't used and Functional, prefix and invisible indexes.

Open in topic →

Spot the bug: WHERE ref = 1234 on a VARCHAR column

ref is an indexed VARCHAR. Why is this a full table scan, and what do the warnings say?

SQL
EXPLAIN SELECT * FROM big_orders WHERE ref = 1234\G
SHOW WARNINGS;
Show answer

Comparing a string column with a number makes MySQL convert every ref value to a number before comparing, which is the same as wrapping the column in a function. The index can't be used:

Result
*************************** 1. row ***************************
EXPLAIN: -> Filter: (big_orders.ref = 1234)  (cost=5061 rows=5005)
    -> Table scan on big_orders  (cost=5061 rows=50045)

+---------+------+-----------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                       |
+---------+------+-----------------------------------------------------------------------------------------------+
| Warning | 1739 | Cannot use ref access on index 'idx_ref' due to type or collation conversion on field 'ref'   |
| Warning | 1739 | Cannot use range access on index 'idx_ref' due to type or collation conversion on field 'ref' |
+---------+------+-----------------------------------------------------------------------------------------------+

With a string literal of the right type, the same index gives a one-row lookup:

SQL
EXPLAIN SELECT * FROM big_orders WHERE ref = 'R0001234'\G
Result
*************************** 1. row ***************************
EXPLAIN: -> Index lookup on big_orders using idx_ref (ref = 'R0001234')  (cost=0.35 rows=1)
What’s happening
  1. MySQL's rule for comparing a string with a number is to compare them as numbers. Many strings convert to the same number ('1234', ' 1234', '1234abc' all become 1234), so the sorted string index can't tell MySQL where to look.
  2. Warning 1739 states it plainly: no ref or range access on idx_ref because of the type conversion.
  3. The reverse case is safe: an INT column compared with a string literal (WHERE id = '42') converts the literal once, and the index is used.
  4. This bug usually arrives through application code: a driver binds a JavaScript number to a VARCHAR column, or a join compares an INT column with a VARCHAR one. Keep join columns the same type and collation — a collation mismatch triggers the same warning.

Learn more: Why an index isn't used.

Open in topic →

LIKE '%1234' vs LIKE 'R00012%' — which can use the index?

Show answer

Only the prefix pattern. A leading wildcard means the value could start with anything, so a sorted index is no help:

SQL
EXPLAIN SELECT * FROM big_orders WHERE ref LIKE '%1234'\G
EXPLAIN SELECT * FROM big_orders WHERE ref LIKE 'R00012%'\G
Result
*************************** 1. row ***************************
EXPLAIN: -> Filter: (big_orders.ref like '%1234')  (cost=5061 rows=5560)
    -> Table scan on big_orders  (cost=5061 rows=50045)

*************************** 1. row ***************************
EXPLAIN: -> Index range scan on big_orders using idx_ref over ('R00012' <= ref <= 'R00012????????????????????????????????????????????????????????'), with index condition: (big_orders.ref like 'R00012%')  (cost=45.3 rows=100)
What’s happening
  1. LIKE 'R00012%' is a range: every value from 'R00012' up to 'R00012' followed by the highest possible characters. The plan shows exactly that range (the ? characters are how EXPLAIN prints "maximum character"), and estimates 100 rows: R0001200 to R0001299.
  2. LIKE '%1234' can match anywhere in the sorted order, so MySQL reads every row and tests the pattern: a table scan.
  3. For "contains" searches on text, use a FULLTEXT index (MATCH … AGAINST) or an external search engine. For "ends with", store a reversed copy of the column in a generated column and index that.
  4. A prefix LIKE is case-insensitive under the default _ci collation and still uses the index, because the index is built with the same collation.

Learn more: Full-text search and Generated columns.

Open in topic →

Why is page 2,001 slow with LIMIT 20 OFFSET 40000, and what's the fix?

SQL
EXPLAIN ANALYZE SELECT id, ref, total FROM big_orders
ORDER BY id LIMIT 20 OFFSET 40000\G

EXPLAIN ANALYZE SELECT id, ref, total FROM big_orders
WHERE id > 40000 ORDER BY id LIMIT 20\G
Show answer

OFFSET still reads every skipped row: to return rows 40,001–40,020, MySQL walks through the first 40,000 and throws them away. Keyset (seek) pagination remembers the last id seen and starts from there, so every page costs the same:

Result
*************************** 1. row ***************************
EXPLAIN: -> Limit/Offset: 20/40000 row(s)  (cost=3245 rows=20) (actual time=3.13..3.13 rows=20 loops=1)
    -> Index scan on big_orders using PRIMARY  (cost=3245 rows=40020) (actual time=0.0496..2.53 rows=40020 loops=1)

*************************** 1. row ***************************
EXPLAIN: -> Limit: 20 row(s)  (cost=3905 rows=20) (actual time=0.0655..0.0675 rows=20 loops=1)
    -> Filter: (big_orders.id > 40000)  (cost=3905 rows=19488) (actual time=0.0536..0.055 rows=20 loops=1)
        -> Index range scan on big_orders using PRIMARY over (40000 < id)  (cost=3905 rows=19488) (actual time=0.0401..0.041 rows=20 loops=1)
What’s happening
  1. EXPLAIN ANALYZE actually runs the query and adds actual time (milliseconds, first row..last row) and actual rows to each step.
  2. The OFFSET plan's index scan produced 40,020 rows to return 20, taking about 3.1 ms on this small, cached table. The cost grows linearly with the page number, and on a real table with wide rows and a cold cache it becomes seconds.
  3. The keyset plan seeks straight to id > 40000 and stops after 20 rows: 0.07 ms. (Its estimated cost is higher because the optimizer doesn't model the early stop well — the actual figures are what count.)
  4. The trade-offs: keyset pagination needs a unique, indexed sort key (use (created_at, id) with a row comparison if you sort by a non-unique column), and it supports "next/previous page" rather than jumping to page 2,001. For infinite scroll and APIs that's exactly right.
  5. Rows inserted or deleted between requests don't cause skipped or repeated items with keyset, which is another reason APIs prefer cursors.

Learn more: Pagination: OFFSET vs keyset and EXPLAIN ANALYZE.

Open in topic →

AUTO_INCREMENT or UUID for the primary key?

Show answer

Default to AUTO_INCREMENT (BIGINT) in InnoDB, and use UUIDs when ids must be generated outside the database or must not be guessable — preferably a time-ordered UUID stored in BINARY(16).

What’s happening
  1. InnoDB stores the table in primary-key order (the clustered index). Increasing keys append to the end of the B+tree; random UUIDv4 keys insert all over it, causing page splits, fragmentation and a much larger working set in the buffer pool.
  2. Every secondary index stores the primary key too, so a 36-character CHAR(36) UUID makes every index bigger. BINARY(16) stores the same value in 16 bytes, versus 8 for a BIGINT.
  3. MySQL's UUID_TO_BIN(uuid, 1) swaps the time fields of a version-1 UUID() so that values sort by time, which fixes most of the insert-order problem; UUIDv7 (time-ordered by design) gives the same benefit when generated by the application.
  4. UUIDs win when clients or several services create ids before inserting (offline apps, merging shards, idempotent APIs) and when you don't want sequential ids exposed in URLs.
  5. A common compromise: an AUTO_INCREMENT primary key for the engine, plus a unique public UUID column for the outside world.

Learn more: Primary keys: AUTO_INCREMENT vs UUID.

Open in topic →

When is denormalising worth it?

Show answer

When a read is frequent, expensive to compute and tolerant of a little staleness — and you have a plan to keep the copy correct. Normalise by default; denormalise deliberately, for a measured reason.

What’s happening
  1. Normalisation stores each fact once, so writes are simple and anomalies impossible. The cost is joins and aggregation on every read.
  2. Good reasons to copy data: a counter shown on every page (posts.comment_count instead of COUNT(*) each time), a summary table for dashboards, a point-in-time value that must not change (order_items.unit_price), or a read model for search.
  3. Every copy needs an owner: update it in the same transaction, with a trigger, or asynchronously from an event or the binlog — and decide how stale it may be.
  4. Try cheaper fixes first: the right index, a covering index, caching in Redis, or a read replica. Denormalising is a schema change that every future writer has to know about.
  5. In MongoDB the trade-off is reversed: embedding (denormalising) is the default, and you normalise when data grows without bound or is shared and updated often.

Learn more: Denormalisation and when it's worth it and Embedding vs referencing.

Open in topic →

EXPLAIN vs EXPLAIN ANALYZE: what's the difference, and what does rows=1 … rows=0 mean here?

SQL
EXPLAIN ANALYZE SELECT * FROM big_orders
WHERE customer_id = 43 AND status = 'pending' AND ordered_at >= '2025-01-01'\G
Show answer

EXPLAIN shows the plan and the optimizer's estimates without running the query; EXPLAIN ANALYZE runs it and adds what actually happened. Here the optimizer estimated 1 row and actually found 0:

Result
*************************** 1. row ***************************
EXPLAIN: -> Index range scan on big_orders using idx_cust_status_date over (customer_id = 43 AND status = 'pending' AND '2025-01-01 00:00:00' <= ordered_at), with index condition: ((big_orders.`status` = 'pending') and (big_orders.customer_id = 43) and (big_orders.ordered_at >= TIMESTAMP'2025-01-01 00:00:00'))  (cost=0.71 rows=1) (actual time=0.0124..0.0124 rows=0 loops=1)
What’s happening
  1. (cost=0.71 rows=1) is the estimate: the optimizer thinks about one row matches. It never estimates 0, so 1 is its "very few" answer.
  2. (actual time=0.0124..0.0124 rows=0 loops=1) is the measurement: time to the first row and to the last row in milliseconds, rows produced, and how many times this step ran. Customer 43's 25 orders in this data are all shipped, so none are pending.
  3. Big gaps between estimated and actual rows point to stale statistics (ANALYZE TABLE), skewed data (consider a histogram) or a misleading predicate — and they're the usual reason for a bad plan.
  4. Because EXPLAIN ANALYZE executes the statement, running it on a slow query takes as long as the query. It's meant for SELECTs: tried on a single-table UPDATE here, it printed -> <not executable by iterator executor> and changed nothing. A plain EXPLAIN never runs anything.
  5. loops matters in joins: an inner step with loops=1000 ran once per outer row, so multiply its time by the loops to see its real cost.

Learn more: EXPLAIN ANALYZE and Selectivity and cardinality.

Open in topic →

What does ACID stand for, in one sentence each?

Show answer

Atomicity: all of a transaction's changes happen or none do. Consistency: a transaction moves the database from one valid state to another, respecting every constraint. Isolation: concurrent transactions don't see each other's half-finished work (to the degree the isolation level promises). Durability: once COMMIT returns, the change survives a crash.

What’s happening
  1. Atomicity is implemented in InnoDB with the undo log: every change records how to reverse it, and ROLLBACK (or crash recovery) replays those records backwards.
  2. Consistency is partly the database's job (primary keys, foreign keys, CHECK, NOT NULL) and partly the application's (business rules like "balance never negative" unless you encode them as constraints).
  3. Isolation is MVCC plus locks. It's the one property with a dial — READ UNCOMMITTED to SERIALIZABLE — because full isolation costs concurrency.
  4. Durability is the redo log, flushed to disk at commit (innodb_flush_log_at_trx_commit = 1, the default), plus the doublewrite buffer for torn pages. Relaxing that setting to 2 or 0 trades up to about a second of commits for speed.
  5. The crisp interview version: "A and D are about crashes, I is about concurrency, C is about rules."

Learn more: Transactions and ACID.

Open in topic →

Predict the second read under REPEATABLE READ and under READ COMMITTED

Session A reads the Pixel's stock twice inside one transaction. Between the reads, session B (autocommit) runs UPDATE stock SET qty = qty - 5 WHERE sku = 'pixel'. To try it, open two mysql prompts and type B's UPDATE in the second while A sleeps.

Starting dataThe stock table
SQL
-- reset before each experiment (the two-row table above)
DROP TABLE IF EXISTS stock;
CREATE TABLE stock (sku VARCHAR(10) PRIMARY KEY, qty INT);
INSERT INTO stock VALUES ('pixel', 20), ('iphone', 0);
SQL
-- session A
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;  -- then: READ COMMITTED
START TRANSACTION;
SELECT qty AS first_read  FROM stock WHERE sku = 'pixel';
DO SLEEP(2);                                   -- B's UPDATE commits here
SELECT qty AS second_read FROM stock WHERE sku = 'pixel';
COMMIT;
Show answer

Under REPEATABLE READ (InnoDB's default) the second read is still 20. Under READ COMMITTED it's 15 — a non-repeatable read.

Result
-- REPEATABLE READ run
+-------------+
| second_read |
+-------------+
|          20 |
+-------------+

-- READ COMMITTED run
+-------------+
| second_read |
+-------------+
|          15 |
+-------------+

In both runs first_read was 20, and a SELECT after A's COMMIT returned 15.

What’s happening
  1. SELECT @@transaction_isolation on this server returns REPEATABLE-READ: MySQL's default, unlike PostgreSQL's and SQL Server's READ COMMITTED.
  2. Under REPEATABLE READ, A's first plain SELECT creates a read view (a snapshot), and every later plain SELECT in the transaction reads from it. B's committed update is newer than the snapshot, so InnoDB reconstructs the old version from the undo log: 20.
  3. Under READ COMMITTED, each statement gets a fresh read view, so the second SELECT sees B's committed 15.
  4. After A commits, a new statement outside the transaction sees 15 in both cases. Nothing was blocked: B's UPDATE didn't wait for A's reads, because plain reads take no locks in InnoDB (that's MVCC).
  5. Neither level shows a dirty read (uncommitted data); only READ UNCOMMITTED does.

Learn more: Isolation levels and MVCC: how InnoDB gives each transaction a snapshot.

Open in topic →

Under REPEATABLE READ, A read 20, B subtracted 5, then A runs qty = qty - 1. What does A read next?

Starting dataThe stock table
SQL
-- reset before each experiment (the two-row table above)
DROP TABLE IF EXISTS stock;
CREATE TABLE stock (sku VARCHAR(10) PRIMARY KEY, qty INT);
INSERT INTO stock VALUES ('pixel', 20), ('iphone', 0);
SQL
-- session A (REPEATABLE READ)
START TRANSACTION;
SELECT qty AS read_1 FROM stock WHERE sku = 'pixel';      -- 20
DO SLEEP(2);                                              -- B: qty = qty - 5, committed
UPDATE stock SET qty = qty - 1 WHERE sku = 'pixel';
SELECT qty AS read_2 FROM stock WHERE sku = 'pixel';
COMMIT;
Show answer

14 — not 19. Writes in InnoDB always work on the latest committed row, not on the transaction's snapshot, and after its own write A sees its own change.

Result
+--------+
| read_1 |
+--------+
|     20 |
+--------+

Query OK, 1 row affected
Rows matched: 1  Changed: 1  Warnings: 0

+--------+
| read_2 |
+--------+
|     14 |
+--------+
What’s happening
  1. read_1 comes from A's snapshot: 20.
  2. B commits 20 − 5 = 15 while A sleeps.
  3. A's UPDATE is a current read: it locks the row and reads its newest committed version, 15, and writes 15 − 1 = 14. If it used the snapshot it would write 19 and silently erase B's change.
  4. read_2 is a plain read again, but a transaction always sees its own changes, so it shows 14. A has now seen 20 and then 14 for the same row — the snapshot isn't "frozen" for rows you've modified.
  5. The same "current read" rule applies to SELECT … FOR UPDATE and FOR SHARE. That's how InnoDB's REPEATABLE READ avoids lost updates for qty = qty - 1 — and why the next question still loses one.

Learn more: Locking reads: FOR UPDATE and FOR SHARE.

Open in topic →

Spot the bug: the stock that should be 14 ends up 19

The application reads the stock, subtracts one in code, and writes the result back. B's qty = qty - 5 commits in between. Why is the final stock 19?

Starting dataThe stock table
SQL
-- reset before each experiment (the two-row table above)
DROP TABLE IF EXISTS stock;
CREATE TABLE stock (sku VARCHAR(10) PRIMARY KEY, qty INT);
INSERT INTO stock VALUES ('pixel', 20), ('iphone', 0);
SQL
-- session A
START TRANSACTION;
SELECT qty AS read_1 FROM stock WHERE sku = 'pixel';      -- app sees 20
DO SLEEP(2);                                              -- B: qty = qty - 5, committed
UPDATE stock SET qty = 19 WHERE sku = 'pixel';            -- app computed 20 - 1
COMMIT;
SELECT qty AS final FROM stock WHERE sku = 'pixel';
Show answer

It's a lost update: A wrote a value it computed from a stale read, overwriting B's committed change. Both transactions succeeded, and five units of stock vanished from the books.

Result
+-------+
| final |
+-------+
|    19 |
+-------+
What’s happening
  1. A's SELECT read 20 from its snapshot. The application computed 19 in memory.
  2. B committed 15. A's UPDATE … SET qty = 19 doesn't read the column at all; it just overwrites the row with 19. No error, no warning.
  3. Fix 1, the simplest: let the database do the arithmetic, SET qty = qty - 1 (previous question) — atomic and correct.
  4. Fix 2, pessimistic locking: read with SELECT qty … FOR UPDATE. B's update then waits until A commits, and A's read sees the real current value.
  5. Fix 3, optimistic locking: add a version column and write … WHERE sku = 'pixel' AND version = <version I read>; if another writer got there first, 0 rows are affected and the application retries (next question).

Learn more: Optimistic vs pessimistic locking.

Open in topic →

Optimistic locking: predict the second update

Two editors both loaded document 1 at version = 3. Editor A saves first, then editor B.

Starting dataThe docs table
SQL
DROP TABLE IF EXISTS docs;
CREATE TABLE docs (id INT PRIMARY KEY, body VARCHAR(50), version INT NOT NULL);
INSERT INTO docs VALUES (1, 'draft', 3);
SQL
UPDATE docs SET body = 'edit by A', version = version + 1 WHERE id = 1 AND version = 3;
UPDATE docs SET body = 'edit by B', version = version + 1 WHERE id = 1 AND version = 3;
SELECT * FROM docs;
Show answer

A's update succeeds and bumps the version to 4; B's matches 0 rows, so it changes nothing and the application knows there was a conflict.

Result
Query OK, 1 row affected
Rows matched: 1  Changed: 1  Warnings: 0

Query OK, 0 rows affected
Rows matched: 0  Changed: 0  Warnings: 0

+----+-----------+---------+
| id | body      | version |
+----+-----------+---------+
|  1 | edit by A |       4 |
+----+-----------+---------+
What’s happening
  1. Both editors read version 3 without taking any lock — that's the "optimistic" part: assume conflicts are rare.
  2. A's WHERE id = 1 AND version = 3 matches, and the row becomes version 4.
  3. B's WHERE … version = 3 no longer matches anything. The affected-row count (0, which drivers return as affectedRows) is the conflict signal.
  4. The application then reloads, merges or asks the user — or, for automatic jobs, retries the read-modify-write.
  5. Choose optimistic locking when conflicts are rare and transactions span user think-time (forms, APIs). Choose SELECT … FOR UPDATE when conflicts are frequent and the whole read-modify-write happens inside one short transaction. ORMs like Sequelize and Prisma-based patterns implement the version check for you.

Learn more: Optimistic vs pessimistic locking.

Open in topic →

Two transactions update pixel and iphone in opposite orders. What happens?

Starting dataThe stock table
SQL
-- reset before each experiment (the two-row table above)
DROP TABLE IF EXISTS stock;
CREATE TABLE stock (sku VARCHAR(10) PRIMARY KEY, qty INT);
INSERT INTO stock VALUES ('pixel', 20), ('iphone', 0);
SQL
-- session A                                   -- session B (starts 0.5 s later)
START TRANSACTION;                             START TRANSACTION;
UPDATE stock SET qty = qty - 1                 UPDATE stock SET qty = qty + 1
  WHERE sku = 'pixel';                           WHERE sku = 'iphone';
DO SLEEP(1);                                   DO SLEEP(1);
UPDATE stock SET qty = qty + 1                 UPDATE stock SET qty = qty - 1
  WHERE sku = 'iphone';                          WHERE sku = 'pixel';
COMMIT;                                        COMMIT;
Show answer

A deadlock: each holds the row the other needs. InnoDB detects the cycle immediately and rolls one transaction back — here B — so the other can finish:

Result
-- session B
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

-- afterwards
+--------+------+
| sku    | qty  |
+--------+------+
| iphone |    1 |
| pixel  |   19 |
+--------+------+
What’s happening
  1. A locks the pixel row; half a second later B locks the iphone row.
  2. A's second update wants iphone and waits for B. B's second update wants pixel and would wait for A — a cycle, which no amount of waiting can resolve.
  3. InnoDB's deadlock detector (on by default, innodb_deadlock_detect) picks a victim — normally the transaction that's cheapest to undo — and rolls all of it back. B's earlier iphone + 1 is undone too.
  4. A then gets the lock, commits, and the final state is A's work only: pixel 19, iphone 1. B's application must retry the whole transaction, which is what the message says.
  5. Prevent most deadlocks by touching rows in a consistent order (for example, sorted by primary key), keeping transactions short, and indexing the columns in your WHERE so fewer rows are locked. SHOW ENGINE INNODB STATUS shows the latest deadlock in detail.

Learn more: Deadlocks and Row, gap and next-key locks.

Open in topic →

Two workers take the next job from a queue table. What does SKIP LOCKED give each, and what does NOWAIT do?

Starting dataThe jobs table
SQL
DROP TABLE IF EXISTS jobs;
CREATE TABLE jobs (id INT PRIMARY KEY, status VARCHAR(10));
INSERT INTO jobs VALUES (1,'queued'),(2,'queued'),(3,'queued');
SQL
-- worker A (keeps its transaction open for 2 s)
START TRANSACTION;
SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

-- worker B, 1 s later
START TRANSACTION;
SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
COMMIT;
START TRANSACTION;
SELECT id FROM jobs WHERE id = 1 FOR UPDATE NOWAIT;
Show answer

A gets job 1, B gets job 2 without waiting. And B's NOWAIT attempt on job 1 fails immediately instead of blocking:

Result
-- worker A
+----+
| id |
+----+
|  1 |
+----+

-- worker B
+----+
| id |
+----+
|  2 |
+----+

ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
What’s happening
  1. A's FOR UPDATE locks job 1 until A commits.
  2. B's query would normally wait on job 1. SKIP LOCKED tells InnoDB to pretend locked rows aren't there, so B's LIMIT 1 lands on job 2.
  3. NOWAIT doesn't skip; it fails at once with error 3572 if a row is locked, so the application can do something else instead of hanging until innodb_lock_wait_timeout (50 s by default).
  4. This is how you build a reliable job queue in MySQL 8.0+: workers claim different rows with no coordination, then mark them running and commit.
  5. Both options are MySQL 8.0.1+. Before that, people used GET_LOCK(), or an UPDATE … SET owner = ? WHERE owner IS NULL LIMIT 1 claim followed by a SELECT.

Learn more: NOWAIT and SKIP LOCKED.

Open in topic →

Predict: what survives this ROLLBACK?

autocommit is on (the default).

Starting dataThe audit table
SQL
DROP TABLE IF EXISTS audit;
CREATE TABLE audit (id INT AUTO_INCREMENT PRIMARY KEY, note VARCHAR(20));
DROP TABLE IF EXISTS scratch_tmp;   -- only needed when you run the question a second time
SQL
START TRANSACTION;
INSERT INTO audit (note) VALUES ('first');
CREATE TABLE scratch_tmp (x INT);
INSERT INTO audit (note) VALUES ('second');
ROLLBACK;
SELECT * FROM audit;
Show answer

Both rows survive. CREATE TABLE causes an implicit commit, which commits 'first' and ends the transaction; 'second' then runs in autocommit mode and commits on its own. The ROLLBACK has nothing left to undo.

Result
+----+--------+
| id | note   |
+----+--------+
|  1 | first  |
|  2 | second |
+----+--------+
What’s happening
  1. START TRANSACTION begins an explicit transaction; 'first' is inserted but not committed.
  2. DDL statements (CREATE, ALTER, DROP, TRUNCATE, RENAME) and some others (LOCK TABLES, START TRANSACTION itself) commit the current transaction first, then run. MySQL DDL isn't transactional in the PostgreSQL sense.
  3. After the implicit commit there's no open transaction, and with autocommit = 1 every statement is its own transaction: 'second' commits immediately.
  4. ROLLBACK with no open transaction is a no-op and isn't an error — which is why this bug is silent.
  5. Keep schema changes out of data transactions. PostgreSQL can roll back CREATE TABLE inside a transaction; MySQL can't.

Learn more: Autocommit and implicit commits.

Open in topic →

A user updates their profile, then reloads and sees the old data. The app reads from replicas. Why, and what do you do?

Show answer

Replication lag. MySQL replication is asynchronous by default: the write commits on the source and reaches the replica a little later, so a read routed to a replica straight after the write can see the old row. The fix is read-your-writes: send that user's reads to the source for a short time after they write, or wait until the replica has applied their transaction.

What’s happening
  1. On commit, the source writes the change to its binary log. A replica's I/O thread copies it into its relay log and its SQL (applier) threads replay it. Lag is the time between those steps — usually milliseconds, but seconds or more under heavy writes or long transactions.
  2. Common fixes: route reads to the source for N seconds after a write (or for the rest of the request); pin a session to the source after a write; or use GTIDs — record the transaction's GTID on write and have the replica WAIT_FOR_EXECUTED_GTID_SET() before reading.
  3. Semi-synchronous replication makes the source wait until at least one replica has received the transaction, which protects against data loss on failover but does not by itself guarantee the replica has applied it, so it doesn't fix this read.
  4. Not every read needs it: product listings can tolerate a second of staleness; "my profile", "my order" and balances usually can't.
  5. This can't be demonstrated in the single-server sandbox; it needs a source and at least one replica.

Learn more: Read replicas and replication lag and Asynchronous, semi-synchronous and group replication.

Open in topic →

Partitioning vs sharding — what's the difference, and when do you need each?

Show answer

Partitioning splits one table into pieces inside one server; the database routes queries to the right pieces. Sharding splits the data across several servers; something above the database (the application, a proxy like Vitess or ProxySQL) has to route each query.

What’s happening
  1. MySQL partitioning (PARTITION BY RANGE (YEAR(ordered_at)), LIST, HASH, KEY) is transparent to queries. Its main wins are partition pruning (a query for 2025 only reads the 2025 partition) and cheap data retention (ALTER TABLE … DROP PARTITION instead of a huge DELETE).
  2. It doesn't add capacity: one server's CPU, memory and disk still serve everything. And every unique key must include the partitioning column, which is a real design constraint.
  3. Sharding adds write capacity and storage by giving each server a subset of rows, chosen by a shard key (often tenant or user id). The cost: cross-shard joins and transactions are hard, rebalancing is work, and every query should include the shard key.
  4. Order of escalation: indexes and query fixes → bigger server (scale up) → read replicas and caching → partitioning for very large tables → sharding when writes or data size exceed one server.
  5. MongoDB has sharding built in (mongos routers, config servers, chunks), which is one reason it's chosen for very large write-heavy workloads; MySQL needs external tooling.

Learn more: Partitioning, Sharding and Scaling up vs scaling out.

Open in topic →

Why use a connection pool, and how big should it be?

Show answer

Opening a MySQL connection is expensive (TCP, TLS, authentication, per-connection server memory) and the server has a hard max_connections limit, so applications keep a pool of open connections and lend them out per query or transaction. Size it small — roughly the number of queries the database can usefully run in parallel — not the number of users.

What’s happening
  1. Without a pool, every request pays the connection setup and the server spends memory on a thread per connection. Under load the server refuses new connections with error 1040, Too many connections.
  2. With a pool (mysql2's createPool, Knex, Prisma, Sequelize all have one), requests borrow a connection, run, and return it. Extra requests queue in the application instead of overloading the database.
  3. A database can only do so much at once: a pool of 10–20 per application instance is typical. Ten instances × 100 connections each is how you exhaust max_connections (151 by default) during a deploy.
  4. Always return connections — release in a finally — or the pool drains and requests hang. Transactions must use one connection from BEGIN to COMMIT.
  5. Serverless functions can't keep a long-lived pool, so they need an external pooler or proxy (RDS Proxy, ProxySQL, PlanetScale-style HTTP drivers) to stop each invocation opening its own connection.

Learn more: Connection pooling and Connection limits in serverless.

Open in topic →

Predict the projection output, and what happens if you mix 1 and 0?

mongosh
db.users.find({ age: { $gt: 30 } }, { name: 1 })
db.users.find({ age: { $gt: 30 } }, { name: 1, _id: 0 })
db.users.find({}, { name: 1, age: 0 })
Show answer

_id is always returned unless you exclude it, so the first query returns _id and name. You can't mix inclusion and exclusion in one projection — the only exception is _id: 0.

Result
ch15> db.users.find({ age: { $gt: 30 } }, { name: 1 })
[ { _id: 1, name: 'Asha' }, { _id: 2, name: 'Ben' } ]
ch15> db.users.find({ age: { $gt: 30 } }, { name: 1, _id: 0 })
[ { name: 'Asha' }, { name: 'Ben' } ]
ch15> db.users.find({}, { name: 1, age: 0 })
Uncaught MongoServerError[Location31254]: Cannot do exclusion on field age in inclusion projection
What’s happening
  1. { age: { $gt: 30 } } matches Asha (41) and Ben (35). Dev has no age, and a missing field never satisfies $gt.
  2. { name: 1 } is an inclusion projection: return only the listed fields — plus _id, which is included by default.
  3. _id: 0 is the one exclusion allowed inside an inclusion projection.
  4. { name: 1, age: 0 } asks for "only name" and "everything except age" at once, which is contradictory, so the server rejects it.
  5. Projections matter for performance too: returning less data means less network traffic, and the right projection can make a query covered (see the explain() question below).

Learn more: Projections.

Open in topic →

Predict four counts on the tags array

mongosh
db.users.countDocuments({ tags: "dev" })
db.users.countDocuments({ tags: ["dev"] })
db.users.countDocuments({ tags: { $all: ["dev", "ops"] } })
db.users.countDocuments({ tags: { $size: 0 } })
Show answer

3, 1, 1, 1.

Result
ch15> db.users.countDocuments({ tags: "dev" })
3
ch15> db.users.countDocuments({ tags: ["dev"] })
1
ch15> db.users.countDocuments({ tags: { $all: ["dev", "ops"] } })
1
ch15> db.users.countDocuments({ tags: { $size: 0 } })
1
What’s happening
  1. { tags: "dev" } on an array field means "the array contains "dev"": Asha, Ben and Dev.
  2. { tags: ["dev"] } means "the array equals exactly ["dev"]" — same elements, same order. Only Ben.
  3. $all means "contains every listed value, in any order, possibly with others". Only Dev has both dev and ops.
  4. $size: 0 matches arrays with exactly zero elements: Chloe. $size only takes an exact number; for "at least N" use { "tags.N-1": { $exists: true } } or $expr with $size.
  5. An index on tags is a multikey index (one entry per element), which is what makes the "contains" query fast.

Learn more: Querying arrays: $size, $all and $elemMatch.

Open in topic →

Who has an exam score above 90? Dotted conditions vs $elemMatch

mongosh
db.users.find({ "scores.type": "exam", "scores.score": { $gt: 90 } }, { name: 1, _id: 0 })
db.users.find({ scores: { $elemMatch: { type: "exam", score: { $gt: 90 } } } }, { name: 1, _id: 0 }).toArray()
Show answer

The first query returns Asha — wrongly: her exam score is 72. The second returns nobody, which is correct.

Result
ch15> db.users.find({ "scores.type": "exam", "scores.score": { $gt: 90 } }, { name: 1, _id: 0 })
[ { name: 'Asha' } ]
ch15> db.users.find({ scores: { $elemMatch: { type: "exam", score: { $gt: 90 } } } }, { name: 1, _id: 0 }).toArray()
[]
What’s happening
  1. Each dotted condition on an array is checked independently: "some element has type: "exam"" and "some element has score > 90".
  2. Asha has an exam element (score 72) and a different element, her quiz, with 95. Both conditions are true, so she matches.
  3. $elemMatch requires one element to satisfy all the conditions together. None of the exam elements has a score above 90, so nothing matches.
  4. Rule: when several conditions must apply to the same embedded document in an array, use $elemMatch. For a single condition, the dotted form is equivalent and shorter.
  5. (.toArray() was added to the second query only so mongosh prints []; an empty cursor prints nothing.)

Learn more: Querying arrays: $size, $all and $elemMatch and Querying embedded documents.

Open in topic →

Predict: missing fields with $lt, $ne and null

Dev has no age field.

mongosh
db.users.countDocuments({ age: { $lt: 40 } })
db.users.countDocuments({ age: { $ne: 35 } })
db.users.countDocuments({ age: null })
Show answer

2, 3, 1. A missing field fails comparisons like $lt, but matches $ne and matches null.

Result
ch15> db.users.countDocuments({ age: { $lt: 40 } })
2
ch15> db.users.countDocuments({ age: { $ne: 35 } })
3
ch15> db.users.countDocuments({ age: null })
1
What’s happening
  1. $lt: 40 matches Ben (35) and Chloe (29). Comparison operators only match values of a comparable type, and a missing field has no value, so Dev is out.
  2. $ne: 35 means "not equal to 35", and a missing field is not equal to 35, so Asha, Chloe and Dev match. That's different from SQL, where age <> 35 would drop a NULL age.
  3. { age: null } matches documents where age is null or missing — Dev here.
  4. To find only documents that lack the field, use { age: { $exists: false } } (also 1 here). To find only an explicit null, use { age: { $type: "null" } }.
  5. Schemaless means the "no value" cases are your job: decide whether documents may omit fields, and enforce it with schema validation if not.

Learn more: Comparison operators and $exists and $type.

Open in topic →

Positional $, $[] and arrayFilters — predict the cart after each update

The cart starts as items: [ { sku: "A", qty: 1 }, { sku: "B", qty: 2 }, { sku: "A", qty: 5 } ].

Starting dataThe cart
mongosh
db.carts.drop();
db.carts.insertOne({ _id: 1, user: "asha", items: [ { sku: "A", qty: 1 }, { sku: "B", qty: 2 }, { sku: "A", qty: 5 } ] });
mongosh
db.carts.updateOne({ _id: 1, "items.sku": "A" }, { $inc: { "items.$.qty": 10 } })
db.carts.findOne({ _id: 1 }).items          // after $
db.carts.updateOne({ _id: 1 }, { $inc: { "items.$[].qty": 100 } })
db.carts.findOne({ _id: 1 }).items          // after $[]
db.carts.updateOne({ _id: 1 }, { $set: { "items.$[it].qty": 0 } }, { arrayFilters: [ { "it.sku": "A" } ] })
db.carts.findOne({ _id: 1 }).items          // after $[it]
Show answer

$ updates only the first matching element, $[] updates every element, and $[it] with arrayFilters updates every element that matches the filter:

Result
ch15> db.carts.updateOne({ _id: 1, "items.sku": "A" }, { $inc: { "items.$.qty": 10 } })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
ch15> db.carts.findOne({ _id: 1 }).items          // after $
[ { sku: 'A', qty: 11 }, { sku: 'B', qty: 2 }, { sku: 'A', qty: 5 } ]
ch15> db.carts.updateOne({ _id: 1 }, { $inc: { "items.$[].qty": 100 } })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
ch15> db.carts.findOne({ _id: 1 }).items          // after $[]
[
  { sku: 'A', qty: 111 },
  { sku: 'B', qty: 102 },
  { sku: 'A', qty: 105 }
]
ch15> db.carts.updateOne({ _id: 1 }, { $set: { "items.$[it].qty": 0 } }, { arrayFilters: [ { "it.sku": "A" } ] })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
ch15> db.carts.findOne({ _id: 1 }).items          // after $[it]
[ { sku: 'A', qty: 0 }, { sku: 'B', qty: 102 }, { sku: 'A', qty: 0 } ]
What’s happening
  1. The positional $ refers to the first array element that matched the query's array condition ("items.sku": "A"). The second A (qty 5) is untouched — the classic surprise. The query must include a condition on the array for $ to work.
  2. $[] (all positional) needs no array condition and applies to every element: each qty goes up by 100.
  3. $[it] is a placeholder named in arrayFilters: { "it.sku": "A" } selects elements with sku A, so both A lines become 0 and B keeps 102.
  4. Each updateOne reported matchedCount: 1, modifiedCount: 1: the counts are about documents, not array elements.
  5. Use $ for "the one element I found", arrayFilters for "these elements", $[] for "all of them". arrayFilters and $[] are MongoDB 3.6+.

Learn more: The positional $ operator and [$[] and arrayFilters](#and-arrayfilters).

Open in topic →

Upsert twice with $setOnInsert — what's createdBy? And what does updateOne({ age: 5 }) do?

Starting dataAn empty people collection
mongosh
db.people.drop();
mongosh
db.people.updateOne({ name: "ankit" }, { $set: { age: 90 }, $setOnInsert: { createdBy: "upsert" } }, { upsert: true })
db.people.updateOne({ name: "ankit" }, { $set: { age: 91 }, $setOnInsert: { createdBy: "upsert-again" } }, { upsert: true })
db.people.find({}, { _id: 0 })
db.people.updateOne({ name: "ankit" }, { age: 5 })
Show answer

The first call inserts (upsertedCount: 1), the second updates. createdBy stays "upsert", because $setOnInsert only applies when the upsert inserts. The last call is rejected: an update document must use operators.

Result
ch15> db.people.updateOne({ name: "ankit" }, { $set: { age: 90 }, $setOnInsert: { createdBy: "upsert" } }, { upsert: true })
{
  acknowledged: true,
  insertedId: ObjectId('6ad24a0c302be24bfe35e2bd'),
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}
ch15> db.people.updateOne({ name: "ankit" }, { $set: { age: 91 }, $setOnInsert: { createdBy: "upsert-again" } }, { upsert: true })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
ch15> db.people.find({}, { _id: 0 })
[ { name: 'ankit', age: 91, createdBy: 'upsert' } ]
ch15> db.people.updateOne({ name: "ankit" }, { age: 5 })
Uncaught MongoInvalidArgumentError: Update document requires atomic operators
What’s happening
  1. Nothing matches { name: "ankit" } at first, so the upsert builds a new document from the query's equality fields (name) plus the $set and $setOnInsert fields, and generates an _id.
  2. The second call matches that document, so it's an ordinary update: $set changes age to 91 and $setOnInsert is ignored.
  3. That makes $setOnInsert the right home for creation-only fields like createdAt and createdBy.
  4. updateOne(filter, { age: 5 }) has no $ operator. The shell (and the Node driver) refuses it with MongoInvalidArgumentError before it reaches the server. To replace a whole document, call replaceOne({ name: "ankit" }, { name: "ankit", age: 5 }) — which here left { name: 'ankit', age: 5 }, createdBy gone.
  5. Upserts race: two concurrent upserts with the same filter can both insert unless a unique index on the filter field makes the second one fail (and retry as an update).

Learn more: Upserts and replaceOne and findOneAndUpdate.

Open in topic →

$lookup and $unwind: predict the document counts

Customers: Rohit (orders 101, 102), Maya (order 103, whose items array is empty) and Zara (no orders).

Starting dataThe customers and orders collections
mongosh
db.customers.drop(); db.orders.drop();
db.customers.insertMany([ { _id: 1, name: "Rohit" }, { _id: 2, name: "Maya" }, { _id: 3, name: "Zara" } ]);
db.orders.insertMany([
  { _id: 101, customerId: 1, total: 957, items: ["laptop", "charger"] },
  { _id: 102, customerId: 1, total: 88,  items: ["book", "book2"] },
  { _id: 103, customerId: 2, total: 1048, items: [] }
]);
mongosh
db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } }, { $project: { _id: 0, name: 1, orderIds: "$orders._id" } } ])
db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } }, { $unwind: "$orders" }, { $count: "n" } ])
db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } }, { $unwind: { path: "$orders", preserveNullAndEmptyArrays: true } }, { $count: "n" } ])
db.orders.aggregate([ { $unwind: "$items" }, { $count: "n" } ])
Show answer

3, 4 and 4. $lookup always produces an array; $unwind makes one document per element and drops documents whose array is empty unless you ask it not to.

Result
ch15> db.customers.aggregate([ { $lookup: { from: "orders", localField: "_id", foreignField: "customerId", as: "orders" } }, { $project: { _id: 0, name: 1, orderIds: "$orders._id" } } ])
[
  { name: 'Rohit', orderIds: [ 101, 102 ] },
  { name: 'Maya', orderIds: [ 103 ] },
  { name: 'Zara', orderIds: [] }
]
ch15> …{ $unwind: "$orders" }, { $count: "n" } ])
[ { n: 3 } ]
ch15> …{ $unwind: { path: "$orders", preserveNullAndEmptyArrays: true } }, { $count: "n" } ])
[ { n: 4 } ]
ch15> db.orders.aggregate([ { $unwind: "$items" }, { $count: "n" } ])
[ { n: 4 } ]
What’s happening
  1. $lookup is a left outer join: every customer stays, with an orders array holding the matches — two for Rohit, one for Maya, an empty array for Zara (the first command shows it).
  2. Plain $unwind turns Rohit into 2 documents and Maya into 1, and removes Zara: 3. That's the inner-join behaviour people don't expect.
  3. preserveNullAndEmptyArrays: true keeps Zara as one document without an orders field: 4 — the true left join.
  4. On orders, $unwind: "$items" gives 2 + 2 + 0 = 4: order 103's empty items array silently drops it. Any count after an $unwind can quietly lose documents.
  5. $group needs an _id: { $group: { _id: null, revenue: { $sum: "$total" } } } totals everything (revenue: 2093, orders: 3 here), while leaving _id out fails with MongoServerError: a group specification must include an _id.

Learn more: $lookup: joining collections, $unwind and $group and accumulators.

Open in topic →

Read the explain(): COLLSCAN vs IXSCAN vs a covered query

events has 5,000 documents, 20 of them with userId: 42. Predict the three numbers before and after creating { userId: 1, ts: 1 }, and for the projection { _id: 0, userId: 1, ts: 1 }.

Starting dataThe events collection
mongosh
db.events.drop();
const docs = [];
for (let i = 1; i <= 5000; i++) docs.push({ _id: i, userId: i % 250, type: ["click","view","buy","share"][i % 4], ts: new Date(Date.UTC(2025, 0, 1) + i * 60000), amount: i % 97 });
db.events.insertMany(docs);
mongosh
function stats(cursor) {
  const s = cursor.explain("executionStats").executionStats;
  return { nReturned: s.nReturned, totalKeysExamined: s.totalKeysExamined, totalDocsExamined: s.totalDocsExamined };
}
stats(db.events.find({ userId: 42 }))
db.events.createIndex({ userId: 1, ts: 1 })
stats(db.events.find({ userId: 42 }))
stats(db.events.find({ userId: 42 }, { _id: 0, userId: 1, ts: 1 }))
stats(db.events.find({ userId: 42 }, { userId: 1, ts: 1 }))
Show answer

Without the index, MongoDB reads all 5,000 documents to return 20. With it, it reads 20 index keys and 20 documents. With a projection the index can satisfy, it reads 0 documents — a covered query.

Result
[Function: stats]
{ nReturned: 20, totalKeysExamined: 0, totalDocsExamined: 5000 }
userId_1_ts_1
{ nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 20 }
{ nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 0 }
{ nReturned: 20, totalKeysExamined: 20, totalDocsExamined: 20 }

In order: no index (COLLSCAN); after createIndex (IXSCAN + FETCH); the projection { _id: 0, userId: 1, ts: 1 } (PROJECTION_COVERED); and { userId: 1, ts: 1 }, which doesn't exclude _id.

What’s happening
  1. The healthy ratio is nReturned ≈ totalKeysExamined ≈ totalDocsExamined. 20 returned from 5,000 examined is the signature of a missing index: the winning plan's stage was COLLSCAN.
  2. After createIndex, the plan is an IXSCAN on userId_1_ts_1 followed by FETCH to load each document: 20 keys, 20 documents.
  3. When the query and projection use only indexed fields, MongoDB answers from the index alone: totalDocsExamined: 0, and the winning plan's stage is PROJECTION_COVERED.
  4. Forgetting _id: 0 breaks coverage, because _id isn't in this index — 20 documents examined again. It's the most common reason a "covered" query isn't.
  5. explain() without arguments shows only the chosen plan (queryPlanner); "executionStats" runs the query and adds the counts; "allPlansExecution" also shows the plans that lost.

Learn more: explain() and executionStats and Covered queries.

Open in topic →

Compound index order: which queries and sorts can use it?

With indexes { userId: 1, ts: 1 } and { type: 1, amount: 1 }, which of these need an in-memory SORT or a COLLSCAN? (Same events collection; the previous question created the first index, the second is created here. planStages is the helper shown after the answer: define it first.)

mongosh
db.events.createIndex({ type: 1, amount: 1 })
planStages(db.events.find({ ts: { $gte: new Date("2025-01-03") } }))
planStages(db.events.find({ userId: 42 }).sort({ ts: -1 }))
planStages(db.events.find({ userId: 42 }).sort({ amount: 1 }))
planStages(db.events.find().sort({ type: 1, amount: -1 }).limit(5))
planStages(db.events.find().sort({ type: -1, amount: -1 }).limit(5))
Show answer

Querying ts alone is a COLLSCAN; sorting by ts after userId uses the index in either direction; sorting by amount needs a SORT; and { type: 1, amount: -1 } can't use { type: 1, amount: 1 }, but its exact reverse { type: -1, amount: -1 } can.

Result
type_1_amount_1
COLLSCAN
FETCH <- IXSCAN
SORT <- FETCH <- IXSCAN
SORT <- COLLSCAN
LIMIT <- FETCH <- IXSCAN

One line per query, in order (ts only; userId sorted by ts descending; userId sorted by amount; type 1, amount -1; type -1, amount -1), each the winning plan's stages, outermost first.

What’s happening
  1. Like MySQL's leftmost-prefix rule, a compound index can serve queries on a prefix of its fields. ts isn't a prefix of { userId, ts }, so the query scans the collection.
  2. With userId fixed by equality, the index entries for user 42 are already sorted by ts, and an index can be walked backwards, so sort({ ts: -1 }) needs no SORT stage.
  3. amount isn't in that index, so the 20 matching documents are fetched and sorted in memory (SORT). Fine for 20, a problem for 20,000: a blocking sort holds every document before returning the first, and past 100 MB it has to spill to temporary files on disk (allowed by default since MongoDB 6.0; an error before that).
  4. A compound index supports a sort on its fields in the same directions or exactly reversed. { type: 1, amount: -1 } is neither, so it fell back to SORT <- COLLSCAN; { type: -1, amount: -1 } is the full reverse and used the index with LIMIT stopping after 5.
  5. This is the ESR rule for designing compound indexes: Equality fields first, then Sort fields, then Range fields.

The helper used for the stage chains (typed at the prompt, defining it prints [Function: planStages]):

mongosh
function planStages(cursor) {
  let p = cursor.explain().queryPlanner.winningPlan;
  p = p.queryPlan || p;
  const out = [];
  while (p) { out.push(p.stage); p = p.inputStage; }
  return out.join(" <- ");
}

Learn more: Single-field and compound indexes and The ESR rule.

Open in topic →

A unique index on email, and two users without an email. What happens?

Starting dataAn empty members collection
mongosh
db.members.drop();
mongosh
db.members.createIndex({ email: 1 }, { unique: true })
db.members.insertOne({ email: "a@x.com" })
db.members.insertOne({ email: "a@x.com" })
db.members.insertOne({ name: "no email 1" })
db.members.insertOne({ name: "no email 2" })
Show answer

The duplicate email fails, as expected — and so does the second document without an email, because a unique index treats a missing field as null, and two nulls are duplicates:

Result
email_1
{
  acknowledged: true,
  insertedId: ObjectId('6b008635de864e3e01911bb3')
}
Uncaught MongoServerError: E11000 duplicate key error collection: ch15.members index: email_1 dup key: { email: "a@x.com" }
{
  acknowledged: true,
  insertedId: ObjectId('6b008635de864e3e01911bb5')
}
Uncaught MongoServerError: E11000 duplicate key error collection: ch15.members index: email_1 dup key: { email: null }

Make it a partial unique index that only covers documents that have the field (after db.members.drop(), so the old index and documents are gone):

mongosh
db.members.createIndex(
  { email: 1 },
  { unique: true, partialFilterExpression: { email: { $exists: true } } }
)

With that index, both email-less documents were inserted, and the duplicate a@x.com still failed with the same E11000 error: 3 documents in total.

What’s happening
  1. E11000 is MongoDB's duplicate-key error code; the message names the collection, the index and the key.
  2. Documents that lack an indexed field are indexed with the value null. Under a unique index, only one such document can exist.
  3. partialFilterExpression indexes only documents matching the filter, so email-less documents aren't in the index at all and can't collide.
  4. The catch: a partial index is only used for queries whose filter implies the partial filter. find({ email: null }) can't use it — its plan was a COLLSCAN.
  5. Older code used sparse: true for the same purpose; partial indexes (3.2+) are the more general, recommended form.

Learn more: Unique and partial indexes.

Open in topic →

Inside a transaction, what does a reader outside it see — and after abortTransaction?

Starting dataThe accounts collection
mongosh
db.accounts.drop();
db.accounts.insertMany([ { _id: "ava", balance: 100 }, { _id: "raj", balance: 50 } ]);
mongosh
const session = db.getMongo().startSession();
const accts = session.getDatabase("ch15").accounts;   // ava: 100, raj: 50
session.startTransaction({ writeConcern: { w: "majority" } });
accts.updateOne({ _id: "ava" }, { $inc: { balance: -30 } });
accts.updateOne({ _id: "raj" }, { $inc: { balance: 30 } });
print("inside txn:", JSON.stringify(accts.find().toArray()));
print("outside txn:", JSON.stringify(db.accounts.find().toArray()));
session.abortTransaction();
print("after abort:", JSON.stringify(db.accounts.find().toArray()));
Show answer

Inside, the transfer is visible; outside, nobody sees it until commit; after abortTransaction() both writes are gone.

Result
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
inside txn: [{"_id":"ava","balance":70},{"_id":"raj","balance":80}]
outside txn: [{"_id":"ava","balance":100},{"_id":"raj","balance":50}]
after abort: [{"_id":"ava","balance":100},{"_id":"raj","balance":50}]

Running the same two updates again and calling session.commitTransaction() left ava: 70, raj: 80 for every reader.

What’s happening
  1. Operations go through the session's database handle (accts); that's what attaches them to the transaction. db.accounts is outside it.
  2. The transaction reads its own writes (70 and 80). Other readers see the last committed state (100 and 50) — snapshot isolation, with no locks taken on the readers' side.
  3. abortTransaction() discards both changes atomically. A crash before commit would do the same.
  4. Multi-document transactions need a replica set (MongoDB 4.0+) or sharded cluster (4.2+); this sandbox runs a one-member replica set for that reason. Single-document updates are atomic without a transaction.
  5. Prefer designs that keep related data in one document so you don't need transactions; when you do use them, keep them short (the default limit is 60 seconds) and retry on TransientTransactionError — the Node driver's session.withTransaction() does that for you.

Write concern is the other half: with { w: 0 } an insert returned acknowledged: false (the client didn't wait for the server at all), while { w: "majority", j: true } waited until a majority had written it to the journal and returned acknowledged: true.

Learn more: Multi-document transactions, When not to use transactions and Write concern.

Open in topic →

Predict the four TTLs

redis-cli
127.0.0.1:6379> SET ch15:session abc EX 60
127.0.0.1:6379> TTL ch15:session
127.0.0.1:6379> SET ch15:session xyz
127.0.0.1:6379> TTL ch15:session
127.0.0.1:6379> SET ch15:session abc EX 60
127.0.0.1:6379> SET ch15:session def KEEPTTL
127.0.0.1:6379> TTL ch15:session
127.0.0.1:6379> TTL ch15:nope
Show answer

60, −1, 60, −2. A plain SET on an existing key removes its expiry; KEEPTTL keeps it; -2 means the key doesn't exist.

Result
127.0.0.1:6379> SET ch15:session abc EX 60
OK
127.0.0.1:6379> TTL ch15:session
(integer) 60
127.0.0.1:6379> SET ch15:session xyz
OK
127.0.0.1:6379> TTL ch15:session
(integer) -1
127.0.0.1:6379> SET ch15:session abc EX 60
OK
127.0.0.1:6379> SET ch15:session def KEEPTTL
OK
127.0.0.1:6379> TTL ch15:session
(integer) 60
127.0.0.1:6379> TTL ch15:nope
(integer) -2
What’s happening
  1. SET … EX 60 stores the value with a 60-second expiry; TTL returns the seconds left.
  2. SET without an expiry option replaces the key entirely, value and TTL, so the key now lives forever: TTL returns -1 ("exists, no expiry"). This is a classic cache bug — an update path that forgets EX makes the entry permanent.
  3. KEEPTTL (Redis 6.0+) changes the value but keeps the existing expiry.
  4. -2 means "no such key" — either never set or already expired. Commands that modify a value in place (INCR, HSET, LPUSH) don't touch the TTL; commands that replace the whole value (SET, GETSET) clear it.
  5. Expired keys are removed lazily (when accessed) and by a background sampler, so memory is reclaimed gradually, not at the exact second.

Learn more: Expiry and eviction.

Open in topic →

Predict INCR on a number and on a name

redis-cli
127.0.0.1:6379> SET ch15:views 10
127.0.0.1:6379> INCR ch15:views
127.0.0.1:6379> INCRBY ch15:views 5
127.0.0.1:6379> SET ch15:name rohit
127.0.0.1:6379> INCR ch15:name
Show answer

11, 16, then an error: Redis stores strings, and INCR only works when the string is an integer.

Result
127.0.0.1:6379> SET ch15:views 10
OK
127.0.0.1:6379> INCR ch15:views
(integer) 11
127.0.0.1:6379> INCRBY ch15:views 5
(integer) 16
127.0.0.1:6379> SET ch15:name rohit
OK
127.0.0.1:6379> INCR ch15:name
(error) ERR value is not an integer or out of range
What’s happening
  1. SET ch15:views 10 stores the string "10". INCR parses it as a 64-bit integer, adds one, stores "11" and returns the new value.
  2. The read-modify-write happens inside the server, in one step. Redis executes commands one at a time on its main thread, so a thousand clients calling INCR at once never lose an increment — unlike GET, add in the app, SET.
  3. "rohit" isn't an integer, so INCR fails and the value is unchanged.
  4. INCR on a missing key treats it as 0, so counters need no initialisation. INCRBYFLOAT handles decimals.
  5. This atomicity is why Redis is the usual home for page-view counters, rate limits and id generators.

Learn more: Data structures.

Open in topic →

Two workers try to take the same lock. What does each get, and how do you release it safely?

redis-cli
127.0.0.1:6379> SET ch15:lock worker-1 NX PX 30000
127.0.0.1:6379> SET ch15:lock worker-2 NX PX 30000
127.0.0.1:6379> GET ch15:lock
Show answer

Worker 1 gets OK, worker 2 gets (nil) — the key already exists — and the lock holds worker 1's token for 30 seconds.

Result
127.0.0.1:6379> SET ch15:lock worker-1 NX PX 30000
OK
127.0.0.1:6379> SET ch15:lock worker-2 NX PX 30000
(nil)
127.0.0.1:6379> GET ch15:lock
"worker-1"
What’s happening
  1. NX means "only set if it does not exist", so exactly one SET wins. PX 30000 attaches a 30-second expiry in the same atomic command, so a crashed holder can't keep the lock forever.
  2. The value is a unique token per holder (a random string in real code, not just a worker name). That's what makes release safe.
  3. Release must check the token and delete in one atomic step, or you can delete someone else's lock after yours expired. The standard way is a tiny Lua script: if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end, run with EVAL.
  4. The expiry is also the weakness: if the holder pauses longer than 30 s (a GC pause, a slow call), the lock expires and a second worker gets in. For correctness-critical work, pass a fencing token (an increasing number) to the resource so it rejects stale holders.
  5. With a single Redis node, a failover can lose a lock that wasn't replicated yet. Redlock (several independent nodes) addresses that, but it's debated; for strict guarantees many teams use the database (SELECT … FOR UPDATE) or a consensus system like etcd or ZooKeeper.

Learn more: Distributed locks.

Open in topic →

Predict a leaderboard with a tie

redis-cli
127.0.0.1:6379> ZADD ch15:board 120 asha 95 ben 120 chloe 80 dev
127.0.0.1:6379> ZREVRANGE ch15:board 0 2 WITHSCORES
127.0.0.1:6379> ZREVRANK ch15:board ben
127.0.0.1:6379> ZINCRBY ch15:board 30 dev
127.0.0.1:6379> LPUSH ch15:board x
Show answer

The top three are chloe 120, asha 120, ben 95 — ties are ordered by member name, and in reverse order that puts chloe first. Ben's rank from the top is 2 (zero-based). Dev rises to 110. LPUSH fails: the key holds a sorted set.

Result
127.0.0.1:6379> ZADD ch15:board 120 asha 95 ben 120 chloe 80 dev
(integer) 4
127.0.0.1:6379> ZREVRANGE ch15:board 0 2 WITHSCORES
1) "chloe"
2) "120"
3) "asha"
4) "120"
5) "ben"
6) "95"
127.0.0.1:6379> ZREVRANK ch15:board ben
(integer) 2
127.0.0.1:6379> ZINCRBY ch15:board 30 dev
"110"
127.0.0.1:6379> LPUSH ch15:board x
(error) WRONGTYPE Operation against a key holding the wrong kind of value
What’s happening
  1. A sorted set keeps members ordered by score, and members with equal scores in lexicographic order of the member string: asha < chloe. ZREVRANGE reverses both, so chloe comes before asha.
  2. Ranks are zero-based: ZREVRANK 2 means third place. ZRANK (lowest first) gave 1 for Ben.
  3. ZINCRBY is atomic like INCR: adding points never loses a concurrent update. Updates and rank lookups are O(log N), which is why sorted sets are the standard leaderboard.
  4. Each key has one type (TYPE ch15:board returns zset); using a command for another type returns WRONGTYPE. Key naming conventions (ch15:board, user:42:cart) are how teams keep track.
  5. To break ties by time instead of name, encode it in the score (for example score * 1e10 + (MAX_TS - ts)), since the score is the only sort key.

Learn more: Data structures.

Open in topic →

Build a limit of N requests per minute per user — predict the counter and the TTL

redis-cli
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
127.0.0.1:6379> EXPIRE ch15:rl:user42:2025-10-16T10:15 60 NX
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
127.0.0.1:6379> EXPIRE ch15:rl:user42:2025-10-16T10:15 60 NX
127.0.0.1:6379> TTL ch15:rl:user42:2025-10-16T10:15
Show answer

The counter goes 1, 2, 3; the first EXPIRE … NX returns 1 (set) and the second 0 (an expiry already exists), so the window isn't extended by later requests.

Result
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
(integer) 1
127.0.0.1:6379> EXPIRE ch15:rl:user42:2025-10-16T10:15 60 NX
(integer) 1
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
(integer) 2
127.0.0.1:6379> INCR ch15:rl:user42:2025-10-16T10:15
(integer) 3
127.0.0.1:6379> EXPIRE ch15:rl:user42:2025-10-16T10:15 60 NX
(integer) 0
127.0.0.1:6379> TTL ch15:rl:user42:2025-10-16T10:15
(integer) 60
What’s happening
  1. This is a fixed-window limiter: one key per user per minute (the minute is in the key name). Each request runs INCR and is rejected if the returned count exceeds N.
  2. The key needs an expiry so old windows disappear. EXPIRE … NX (Redis 7.0+) only sets it if none exists, so it's safe to send on every request; on older versions, set it only when INCR returned 1.
  3. Run the two commands in one round trip (MULTI/EXEC or a pipeline), or in a Lua script, so a crash between them can't leave a counter with no expiry.
  4. The weakness of fixed windows is the boundary: a user can send N requests at 10:15:59 and N more at 10:16:00. A sliding window (a sorted set of request timestamps, trimmed with ZREMRANGEBYSCORE) or a token bucket smooths that out at a higher cost.
  5. Because every app server talks to the same Redis, the limit holds across a whole fleet — the reason to use Redis rather than an in-memory counter per process.

Learn more: Rate limiting with Redis.

Open in topic →

Cache-aside: walk through a read and a write, and say what goes wrong under load

Show answer

Read: check Redis; on a miss, read the database, store the result with a TTL, return it. Write: update the database, then delete the cache key (don't update it). Under load, the classic failure is a stampede: a hot key expires and hundreds of requests miss at once and all hit the database.

Result
127.0.0.1:6379> SET ch15:product:7 '{"name":"USB-C Charger","price":29}' PX 200
OK
127.0.0.1:6379> GET ch15:product:7
"{\"name\":\"USB-C Charger\",\"price\":29}"
-- 300 ms later
127.0.0.1:6379> GET ch15:product:7
(nil)
127.0.0.1:6379> EXISTS ch15:product:7
(integer) 0
What’s happening
  1. The entry above was cached with a 200 ms TTL to make expiry visible: read straight away it's there; 300 ms later GET returns (nil) and EXISTS returns 0. In the application, (nil) is the cache miss that triggers a database read and a fresh SET … EX.
  2. Deleting on write (instead of writing the new value into the cache) avoids a race where two concurrent writers leave the older value in Redis. The next read repopulates it from the database.
  3. There's still a small window where a reader caches a value read just before the write committed. TTLs bound how long any such staleness can last — always set one.
  4. Stampede defences: a short lock (SET key:lock NX PX) so only one request rebuilds while others wait or serve stale data; random jitter on TTLs so keys don't expire together; or refreshing hot keys early, before they expire.
  5. Write-through (update the cache synchronously with the database) and write-behind (write to the cache, flush to the database later) are the alternatives; write-behind is fast but can lose writes if Redis fails first.

Learn more: Caching patterns: cache-aside, write-through and write-behind and Cache invalidation and stampedes.

Open in topic →

What happens on this server when Redis runs out of memory, and what survives a restart?

redis-cli
127.0.0.1:6379> CONFIG GET maxmemory
127.0.0.1:6379> CONFIG GET maxmemory-policy
127.0.0.1:6379> CONFIG GET save
127.0.0.1:6379> CONFIG GET appendonly
Show answer

With these defaults Redis has no memory limit of its own (maxmemory 0) and the policy is noeviction: if a limit is set and reached, writes fail with an out-of-memory error rather than dropping data. For persistence it takes RDB snapshots on a schedule and the AOF is off, so a crash can lose the writes since the last snapshot.

Result
127.0.0.1:6379> CONFIG GET maxmemory
1) "maxmemory"
2) "0"
127.0.0.1:6379> CONFIG GET maxmemory-policy
1) "maxmemory-policy"
2) "noeviction"
127.0.0.1:6379> CONFIG GET save
1) "save"
2) "3600 1 300 100 60 10000"
127.0.0.1:6379> CONFIG GET appendonly
1) "appendonly"
2) "no"
What’s happening
  1. maxmemory 0 means "no limit" on 64-bit systems: Redis grows until the OS or the container stops it. Production caches should set maxmemory explicitly.
  2. For a cache, set a policy such as allkeys-lru or allkeys-lfu (evict the least recently or least frequently used keys) or volatile-ttl (only keys with an expiry). noeviction is right when Redis holds data you can't lose, like queues or sessions.
  3. save 3600 1 300 100 60 10000 means: snapshot after 3,600 s if at least 1 key changed, after 300 s if 100 changed, after 60 s if 10,000 changed. Snapshots are compact and fast to load, but everything since the last one is lost in a crash.
  4. The AOF (appendonly yes) logs every write; with appendfsync everysec (the usual setting) you lose at most about a second. Many deployments use both: AOF for durability, RDB for backups and fast restarts.
  5. These values were read from the sandbox's default configuration; this server wasn't pushed to its memory limit, because it's shared with other work.

Learn more: Expiry and eviction and Persistence: RDB and AOF.

Open in topic →

Pub/Sub or Streams for "send a welcome email when a user signs up"?

redis-cli
127.0.0.1:6379> PUBLISH ch15:news "hello"
127.0.0.1:6379> XADD ch15:stream '*' event signup user 42
127.0.0.1:6379> XADD ch15:stream '*' event order user 42
127.0.0.1:6379> XGROUP CREATE ch15:stream mailers 0
127.0.0.1:6379> XREADGROUP GROUP mailers worker-1 COUNT 1 STREAMS ch15:stream '>'
127.0.0.1:6379> XREADGROUP GROUP mailers worker-2 COUNT 1 STREAMS ch15:stream '>'
127.0.0.1:6379> XPENDING ch15:stream mailers
Show answer

Streams. PUBLISH returned 0: nobody was subscribed, so the message is simply gone. A stream stores entries, and a consumer group hands each entry to one worker and tracks it as pending until it's acknowledged.

Result
127.0.0.1:6379> PUBLISH ch15:news "hello"
(integer) 0
127.0.0.1:6379> XADD ch15:stream '*' event signup user 42
"1792165895341-0"
127.0.0.1:6379> XADD ch15:stream '*' event order user 42
"1792165895410-0"
127.0.0.1:6379> XGROUP CREATE ch15:stream mailers 0
OK
127.0.0.1:6379> XREADGROUP GROUP mailers worker-1 COUNT 1 STREAMS ch15:stream '>'
1) 1) "ch15:stream"
   2) 1) 1) "1792165895341-0"
         2) 1) "event"
            2) "signup"
            3) "user"
            4) "42"
127.0.0.1:6379> XREADGROUP GROUP mailers worker-2 COUNT 1 STREAMS ch15:stream '>'
1) 1) "ch15:stream"
   2) 1) 1) "1792165895410-0"
         2) 1) "event"
            2) "order"
            3) "user"
            4) "42"
127.0.0.1:6379> XPENDING ch15:stream mailers
1) (integer) 2
2) "1792165895341-0"
3) "1792165895410-0"
4) 1) 1) "worker-1"
      2) "1"
   2) 1) "worker-2"
      2) "1"
What’s happening
  1. Pub/Sub is fire-and-forget: PUBLISH returns the number of subscribers that received the message. If a subscriber is down or not yet connected, it never sees it. Good for live notifications, bad for jobs.
  2. XADD … * appends an entry with an auto-generated id (<milliseconds>-<sequence>) and keeps it in the stream.
  3. XGROUP CREATE … 0 creates a consumer group that starts from the beginning. XREADGROUP … '>' means "give me entries never delivered to this group", so worker 1 got the signup and worker 2 the order: the work is shared, not duplicated.
  4. XPENDING shows both entries as delivered but unacknowledged, one per worker. A worker calls XACK after sending the email; if it crashes first, another worker can take over the entry with XCLAIM or XAUTOCLAIM.
  5. Streams give you at-least-once delivery, so the email job must be idempotent. For very high volume, long retention or replay across many teams, Kafka is the usual step up.

Learn more: Pub/Sub and Streams.

Open in topic →

Redis, Valkey and the licence question — what changed, and does it matter for your app?

Show answer

Redis moved from BSD to source-available licences (RSALv2/SSPLv1) in 2024; the Linux Foundation forked the last BSD version as Valkey; and Redis 8 (2025) added AGPLv3 as a third option. For an application that just uses Redis as a server, none of the licences restrict you; they matter mainly to companies offering Redis as a hosted service.

What’s happening
  1. Redis 7.4 (2024) switched from the 3-clause BSD licence to a dual RSALv2 / SSPLv1 licence, which forbids offering Redis itself as a managed service without an agreement.
  2. In response, Valkey forked Redis 7.2.4 under BSD, backed by AWS, Google and others; several clouds' managed "Redis" services moved to it.
  3. Redis 8 added AGPLv3 — an OSI-approved open-source licence with a network clause — alongside the other two, and folded features that used to be in Redis Stack (JSON, the query engine, probabilistic types, time series) into the core.
  4. For you: client libraries and the protocol are the same, so application code works against Redis or Valkey. The decisions are about features (Redis 8's built-in modules) and which managed service you use.
  5. This sandbox runs Redis 8.10 (redis_version:8.10.2 in INFO server). Licence details change; check redis.io and valkey.io before quoting them in a legal context.

Learn more: Redis, Valkey and licensing.

Open in topic →

Explain CAP — and why PACELC is the better question

Show answer

CAP: when a network partition happens, a distributed database must choose between consistency (every read sees the latest write, or errors) and availability (every request gets an answer, possibly stale). You can't opt out of partitions, so "CA" isn't a real choice for a distributed system. PACELC adds: Else, when there's no partition, you still trade latency against consistency — which is the trade-off you live with every day.

What’s happening
  1. A partition is when nodes can't reach each other. A CP system (MongoDB with majority writes, etcd, ZooKeeper) refuses writes on the minority side to stay consistent. An AP system (Cassandra, DynamoDB with eventual reads) keeps answering on both sides and reconciles later.
  2. "C" in CAP means linearisability — not the "C" in ACID, which is about constraints. Mixing them up is a common interview slip.
  3. PACELC: if Partition, choose A or C; Else choose Latency or Consistency. Synchronous replication to a majority (consistent) costs a round trip on every write; asynchronous replication (lower latency) allows stale replica reads.
  4. Most systems are tunable per operation: MongoDB's write concern and read concern, Cassandra's consistency levels, MySQL's semi-sync replication and whether you read from replicas.
  5. A good answer ties it to the product: "For balances I want CP behaviour and accept errors during a partition; for a product catalogue, AP and slightly stale reads are fine."

Learn more: CAP and PACELC and Consistency models.

Open in topic →

You're designing an online store. Where do orders, the product catalogue, sessions and sales analytics live?

Show answer

A reasonable answer: orders and payments in a relational database (MySQL or PostgreSQL) for transactions and constraints; the catalogue in the same database, or in MongoDB if products have very different attributes per category; sessions, carts and caches in Redis; and analytics in a column store or warehouse fed from the operational database — not by running big reports on the OLTP database.

What’s happening
  1. Orders need multi-row transactions (order, items, stock, payment), foreign keys and reliable reporting — the relational model's strengths. "Money goes in SQL" is a sound default.
  2. A catalogue with flexible, nested attributes (laptops have RAM and CPU, books have ISBN and author) fits documents well; a JSON column in MySQL or JSONB in PostgreSQL is often enough before adding a second database.
  3. Sessions and carts are small, key-based, short-lived and read constantly: Redis with TTLs. Losing a cart is annoying; losing an order is not acceptable, so the choice of store follows the cost of losing data.
  4. Analytics is OLAP: scans and aggregates over millions of rows, few writers. Column stores (ClickHouse, BigQuery, Snowflake, Redshift) read only the columns a query needs and compress well; feeding them by change-data-capture from the binlog keeps the OLTP database fast.
  5. Every extra database adds operations, consistency work (keeping copies in sync) and on-call burden. Start with one relational database plus Redis, and add others when a measured need appears — that's polyglot persistence done deliberately.

Learn more: A decision guide, OLTP vs OLAP and Polyglot persistence.

Open in topic →

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.