SQL & MySQL Interview Questions 31-35 (Internals: Deadlocks, Engines, Caching)
Hello! In our previous lessons, we've covered how to structure and query databases. Now, we're going to look deeper under the hood.
This lesson is about the engine of the database. We'll cover what happens when concurrent requests collide (deadlocks), the different "engine types" that MySQL uses to store data (InnoDB vs. MyISAM), and the critical mechanisms that make MySQL fast, like the Buffer Pool. Understanding these concepts shows a mature grasp of how a database really works.
31. What is deadlock? How do you detect and fix it?
A deadlock is a concurrency problem where two (or more) transactions are stuck, each waiting for a resource that the other transaction holds. This creates a circular dependency where neither can proceed, and they wait forever.
Analogy: The Hallway Standoff
Imagine two people, Transaction A and Transaction B, meeting in a narrow hallway.
- 1. A wants to get past B, so they step to their left, locking that space.
- 2. At the exact same time, B wants to get past A, so they step to their left, locking that space.
- 3. Now, A is waiting for B to move from the space B is blocking.
- 4. And B is waiting for A to move from the space A is blocking.
They are in a deadlock. Neither can move, and they will be stuck until someone (the database) intervenes.
SQL Deadlock Example:
Imagine two transactions running at the same time:
-- Transaction 1
START TRANSACTION;
UPDATE Accounts SET balance = balance - 100 WHERE id = 1;
-- Now it wants to update row 2
UPDATE Accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- Transaction 2 (at the same time)
START TRANSACTION;
UPDATE Accounts SET balance = balance - 50 WHERE id = 2;
-- Now it wants to update row 1
UPDATE Accounts SET balance = balance + 50 WHERE id = 1;
COMMIT;
How it happens:
- 1. T1 locks row 1.
- 2. T2 locks row 2.
- 3. T1 tries to lock row 2, but T2 holds it. T1 waits.
- 4. T2 tries to lock row 1, but T1 holds it. T2 waits.
- DEADLOCK.
How to Detect and Fix:
- Detection (by MySQL): InnoDB's deadlock detector is constantly monitoring. When it spots a circular wait, it automatically fixes it by choosing one transaction as the "victim." It rolls back (cancels) the victim, which releases its locks, allowing the other transaction to proceed. The application for the victim gets an error (e.g., `Error 1213: Deadlock found...`).
- Detection (by You): If you suspect deadlocks, you run:
In the output, you can find a "LATEST DETECTED DEADLOCK" section that shows you exactly which queries and locks were involved.SHOW ENGINE INNODB STATUS; - Prevention (Your Job):
- Lock in Consistent Order: The best fix. Ensure all your application code, if it needs to lock rows 1 and 2, always locks 1 first, then 2. This breaks the circular wait.
- Keep Transactions Small: Make your transactions short and fast. The less time they hold locks, the lower the chance of a collision.
32. What are MySQL storage engines?
A storage engine is the underlying software component that MySQL uses to create, read, update, and delete data (CRUD) in a table.
Analogy: Think of MySQL Server as a car chassis. The storage engine is the engine you choose to put in it.
- You can put in a `V8` engine (like MyISAM) that is incredibly fast for simple reads but is unreliable and doesn't have safety features.
- Or, you can put in a modern hybrid engine (like InnoDB) that has transactions, crash recovery, and safety features (ACID compliance), and is still very fast.
MySQL lets you choose the engine per table, so you can mix and match. However, InnoDB is the default and the best choice for 99.9% of modern applications.
-- Create a table using the default InnoDB engine
CREATE TABLE MyTable1 (id INT) ENGINE=InnoDB;
-- Create a table using the older MyISAM engine
CREATE TABLE MyTable2 (id INT) ENGINE=MyISAM;
-- See the storage engine for a table
SHOW TABLE STATUS LIKE 'MyTable1';
Sample Output (from `SHOW...`):
+---------+--------+ ...
| Name | Engine | ...
+---------+--------+ ...
| MyTable1| InnoDB | ...
+---------+--------+ ...
1 row in set
33. What is the difference between InnoDB and MyISAM?
This is the most common storage engine comparison. The short answer is that InnoDB is the modern, reliable default, and MyISAM is the legacy engine that you should generally avoid.
| Feature | InnoDB (Default) | MyISAM (Legacy) |
|---|---|---|
| ACID Transactions | Yes. This is the biggest feature. | No. Operations are atomic, but no rollbacks. |
| Locking | Row-level locking. Very high concurrency. | Table-level locking. Very poor concurrency. |
| Foreign Keys | Yes. Enforces referential integrity. | No. Does not enforce integrity. |
| Crash Recovery | Excellent. Uses transaction logs. | Poor. Data can be easily corrupted. |
| Use Case | The default for almost everything. (Web apps, e-commerce, etc.) | Legacy systems or read-only data warehouses. (Was once used for full-text search, but InnoDB is now better). |
Tip: The key difference to remember is locking. If you update one row in a MyISAM table, the entire table is locked, and no one else can even read from it until you are done. In InnoDB, only the single row is locked. This makes InnoDB infinitely better for a web application with many concurrent users.
34. Explain the concept of the MySQL buffer pool.
The InnoDB buffer pool is the most important memory area for an InnoDB database. It's a large cache in RAM where InnoDB holds copies of both data pages and index pages that it has recently accessed from disk.
Analogy: A Carpenter's Workbench
Imagine your database is a giant warehouse of wood (the hard disk, which is slow). You are a carpenter (the MySQL server).
- The Buffer Pool is your workbench (RAM, which is fast).
- When you need to work on a piece of wood (a data page), you don't work on it in the warehouse. You fetch it and put it on your workbench.
- When you're done, you leave it on the workbench. If you need that same piece again, it's already there, saving you a trip (a disk read).
- If the workbench gets full, you take the "least recently used" piece of wood and put it back in the warehouse.
Reading from RAM (the buffer pool) is thousands of times faster than reading from disk. Therefore, the #1 goal of performance tuning a MySQL server is to make the buffer pool large enough to hold the "working set" (the most frequently accessed data and indexes) of your application.
35. What is MySQL Query Cache? Why is it deprecated?
The Query Cache was a feature in older MySQL versions (deprecated in 5.7, removed in 8.0) that tried to improve performance by caching the literal text of a `SELECT` query and itsexact result set.
Analogy: Imagine a simple, lazy cashier.
- Customer 1: "What is the price of milk?"
- Cashier (looks it up): "$3.00" They write on a memo pad: "What is the price of milk?" = $3.00.
- Customer 2: "What is the price of milk?"
- Cashier (reads memo): "$3.00" (This is fast!)
- Customer 3: "What is the price of milk?" (different capitalization)
- Cashier (looks it up): "$3.00" The cache missed because the text wasn't identical.
Why it was deprecated:
The query cache sounds good in theory, but it was terrible in practice, especially for modern web applications.
- It was too fragile: The moment any data in a table was changed (an `INSERT`, `UPDATE`, or `DELETE`), MySQL had to instantly invalidate and delete all cached queries that touched that table.
- It was a bottleneck: In a write-heavy application (like most web apps), the database spent more time invalidating and deleting cache entries than it did serving them. This created a global lock that could slow down the entire server.
- Modern alternatives are better: The InnoDB Buffer Pool (which caches data pages, not query results) and application-level caching (like Redis) are far more efficient and scalable.