Skip to main content
Databases & Storage

MySQL Interview Questions

All Levels (Junior to Staff)16 Questions

MySQL InnoDB engine internals: redo and undo logging, buffer pool tuning, MVCC, gap locks, replication lag mitigation, and high-concurrency connection pooling.

24 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice MySQL Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How does the InnoDB Clustered Index differ from a Secondary Index, and what is a bookmark lookup?

Senior Engineering Answer

In InnoDB, every table is physically organized as a B+ Tree sorted by its Primary Key—this IS the Clustered Index, meaning full row data lives directly inside the leaf nodes of the primary key B+ Tree. (If no PK exists, InnoDB picks the first unique non-null index or generates a hidden 6-byte `DB_ROW_ID`.) Secondary indexes store only the indexed columns plus the Primary Key value in their leaf nodes. Looking up rows via a non-covering secondary index therefore requires a two-step 'bookmark lookup' (back-to-table): first traversing the secondary B+ Tree to get the PK, then traversing the Clustered Index to fetch the remaining columns.

Production Code Example
-- Covering index avoids the second Clustered Index lookup:
CREATE INDEX idx_orders_user_status_total ON orders (user_id, status, total_cents);
SELECT total_cents FROM orders WHERE user_id = 42 AND status = 'paid';
Common Interview Trap / Anti-Pattern:

Using a wide VARCHAR(128) or random UUIDv4 as the Primary Key in InnoDB: every single secondary index embeds a copy of the PK, bloating all indexes and causing random B+ Tree page splits on inserts.

Question #2FundamentalJunior

What are the key differences between InnoDB and MyISAM, and why is utf8mb4 mandatory instead of utf8 in MySQL?

Senior Engineering Answer

InnoDB is MySQL's default ACID-compliant engine featuring row-level locking, MVCC, crash recovery via redo/undo logs, and foreign key enforcement. Legacy MyISAM lacks transactions, crash safety, and MVCC, and uses coarse table-level locking where any write blocks all reads. Separately, MySQL's legacy `utf8` (now aliased to `utf8mb3`) only encodes up to 3 bytes per character and silently rejects or truncates 4-byte Unicode characters (emojis, many CJK and mathematical symbols); always use `utf8mb4` (default in MySQL 8.0+).

Production Code Example
CREATE TABLE users (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    display_name VARCHAR(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Common Interview Trap / Anti-Pattern:

Assuming `utf8` in MySQL supports full UTF-8, or forgetting that `utf8mb4` uses up to 4 bytes per character when sizing indexed `VARCHAR` columns against InnoDB's 3072-byte index key prefix limit.

Question #3FundamentalJunior

How do CHAR vs VARCHAR and INT(11) vs BIGINT behave in MySQL storage and display?

Senior Engineering Answer

`CHAR(N)` allocates fixed-width storage padded for fixed-length codes (like 2-char country codes or fixed hashes), whereas `VARCHAR(N)` stores variable-length strings plus a 1-byte (if max bytes <= 255) or 2-byte length prefix. Importantly, in `INT(11)`, the `11` is NOT the storage size or maximum value—an `INT` is always 4 bytes (signed range -2.14B to +2.14B); the `(11)` was only a display-width hint for `ZEROFILL` (deprecated in MySQL 8.0.17+). Use `BIGINT` (8 bytes) for auto-increment primary keys on high-growth tables to prevent 32-bit PK exhaustion.

Production Code Example
-- Use BIGINT UNSIGNED for high-volume event/order IDs to avoid 2.1B signed INT overflow
ALTER TABLE audit_logs MODIFY COLUMN id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT;
Common Interview Trap / Anti-Pattern:

Evaluating memory usage for temporary tables: MySQL converts `VARCHAR(1000)` to a fixed 1000-char (4000-byte in utf8mb4) buffer inside legacy in-memory `MEMORY` temp tables—so arbitrarily setting `VARCHAR(255)` or `VARCHAR(2000)` everywhere inflates temp table memory.

Question #4FundamentalJunior

How do you interpret the key columns of MySQL EXPLAIN (type, key, rows, Extra) and EXPLAIN ANALYZE?

Senior Engineering Answer

In `EXPLAIN`, `type` ranks access efficiency from best to worst: `const`/`system` (single PK/unique match), `eq_ref` (1-to-1 join on PK/unique), `ref` (non-unique index lookup), `range` (index range scan), `index` (full index scan), and `ALL` (full table scan). `key` shows the chosen index, `rows` estimates examined rows, and `Extra` flags bottlenecks: `Using index` (good: covering index), `Using index condition` (Index Condition Pushdown), `Using filesort` (extra sort pass because ORDER BY didn't match index order), and `Using temporary` (internal temp table for GROUP BY/DISTINCT). MySQL 8.0.18+ adds `EXPLAIN ANALYZE`, which executes the query and prints actual timings and loop row counts.

Production Code Example
EXPLAIN ANALYZE
SELECT customer_id, SUM(total_cents)
FROM orders
WHERE created_at >= '2026-01-01'
GROUP BY customer_id;
Common Interview Trap / Anti-Pattern:

Misreading `Using filesort` as 'always spilling to disk': filesort simply means MySQL had to run an explicit sort algorithm (in `sort_buffer_size` RAM first, spilling to disk only if the buffer is exceeded).

Question #5IntermediateMid-Level

How does InnoDB implement MVCC using hidden row columns, Undo Logs, and Read Views?

Senior Engineering Answer

Every InnoDB row includes hidden metadata: `DB_TRX_ID` (6-byte ID of the last transaction that inserted or updated the row) and `DB_ROLL_PTR` (7-byte pointer into the Undo Log). When a transaction updates a row, InnoDB writes the previous values to the Undo Log and updates the row in place with the new `DB_TRX_ID` and `DB_ROLL_PTR`. When another transaction runs a plain `SELECT` (consistent non-locking read), InnoDB checks the row's `DB_TRX_ID` against the reader's `Read View` (created once at transaction start in `REPEATABLE READ`, or per statement in `READ COMMITTED`); if unseen, InnoDB walks the `DB_ROLL_PTR` undo chain until finding a committed version visible to that Read View.

Production Code Example
-- In REPEATABLE READ, a consistent snapshot is established on the FIRST plain SELECT,
-- NOT at START TRANSACTION (unless START TRANSACTION WITH CONSISTENT SNAPSHOT is used).
START TRANSACTION WITH CONSISTENT SNAPSHOT;
SELECT balance FROM accounts WHERE id = 1;
Common Interview Trap / Anti-Pattern:

Assuming `SELECT ... FOR UPDATE` or `UPDATE` reads from the same MVCC snapshot as plain `SELECT`: locking reads and DML always perform a 'current read' against the latest committed row version—causing 'phantom-like' surprises if mixed with snapshot reads in the same transaction.

Question #6IntermediateMid-Level

Explain InnoDB Record Locks, Gap Locks, and Next-Key Locks, and how they prevent phantom reads under Repeatable Read.

Senior Engineering Answer

Under `REPEATABLE READ` (InnoDB's default), locking reads (`SELECT ... FOR UPDATE`), updates, and deletes use three lock types on index records: (1) Record Lock (locks an existing index record), (2) Gap Lock (locks the open interval between two index records, preventing new inserts into that gap), and (3) Next-Key Lock (a Record Lock + Gap Lock covering `(prev_key, current_key]`). Because Next-Key Locks block other transactions from inserting new rows into scanned index ranges, InnoDB prevents phantom reads even for locking reads—though if a `WHERE` clause matches no index, InnoDB locks every row and gap across the entire Clustered Index (effectively locking the whole table!).

Production Code Example
-- Unique index equality match downgrades Next-Key Lock to a single Record Lock:
SELECT * FROM users WHERE id = 100 FOR UPDATE;
-- Non-unique range match acquires Next-Key + Gap locks on the range:
SELECT * FROM orders WHERE user_id = 42 FOR UPDATE;
Common Interview Trap / Anti-Pattern:

Running `REPEATABLE READ` in high-concurrency write workloads with non-unique range updates when `READ COMMITTED` suffices: Gap Locks frequently cause unexpected insert deadlocks (two transactions hold overlapping gap locks and wait to insert into each other's gaps).

Question #7IntermediateMid-Level

How does the InnoDB Buffer Pool work (LRU midpoint insertion) and what role does the Change Buffer play?

Senior Engineering Answer

The InnoDB Buffer Pool caches 16KB table and index pages in RAM (typically sized to 60-80% of dedicated DB memory). To prevent full-table scans or mysqldumps from evicting hot working-set pages, InnoDB's LRU list uses a midpoint insertion strategy: newly read pages enter at the head of the 'old' sublist (default 37% of the LRU) and only promote to the 'new' (young) sublist if accessed again after `innodb_old_blocks_time` (default 1000ms). Separately, the Change Buffer caches modifications to non-unique secondary index pages not currently in the Buffer Pool, merging them asynchronously when those pages are later read—avoiding random disk I/O on write-heavy workloads.

Production Code Example
-- Check Buffer Pool hit rate and dirty page ratio in MySQL
SHOW ENGINE INNODB STATUS\G
-- Target buffer pool read hit rate > 99% for OLTP workloads
Common Interview Trap / Anti-Pattern:

Leaving `innodb_buffer_pool_size` at its tiny 128MB default on a production server, or forgetting that unique secondary indexes cannot use the Change Buffer because uniqueness must be verified synchronously.

Question #8IntermediateMid-Level

How do InnoDB Online DDL algorithms (INSTANT, INPLACE, COPY) work, and why can Metadata Locks (MDL) still cause outages?

Senior Engineering Answer

MySQL 8.0 supports three DDL algorithms: `INSTANT` (updates only data dictionary metadata—adding/dropping columns in 8.0.29+ completes in milliseconds with zero table rebuild), `INPLACE` (modifies index/table structures without copying rows through the server layer and permits concurrent DML via online row logs), and `COPY` (creates a shadow table and copies rows while blocking concurrent writes). However, even an `INSTANT` DDL must briefly acquire an exclusive Metadata Lock (MDL) at the start/end. If an uncommitted long-running `SELECT` holds a shared MDL, the `ALTER TABLE` blocks waiting for the exclusive MDL—and every subsequent query on that table queues behind the waiting `ALTER TABLE`, halting traffic!

Production Code Example
-- Always specify ALGORITHM and LOCK explicitly to fail fast rather than silently falling back to COPY
ALTER TABLE orders
  ADD COLUMN channel VARCHAR(32) NULL,
  ALGORITHM=INSTANT, LOCK=NONE;
Common Interview Trap / Anti-Pattern:

Running `ALTER TABLE` during peak hours without `SET SESSION lock_wait_timeout = 5` or tools like `gh-ost` / `pt-online-schema-change` when table rebuilds are required.

Question #9AdvancedSenior

Explain the InnoDB Redo Log (WAL), Undo Log, and Doublewrite Buffer in crash recovery.

Senior Engineering Answer

InnoDB guarantees durability without flushing random 16KB data pages synchronously on every commit using Write-Ahead Logging (WAL). Modifications update Buffer Pool pages in memory (marking them dirty) and append physical page deltas sequentially to the Redo Log (`ib_logfile` / `#ib_redo*`). On crash recovery, InnoDB replays committed Redo Log entries forward and rolls back uncommitted transactions using the Undo Log. Because InnoDB pages are 16KB while OS filesystems write in 4KB blocks, a power loss mid-flush can create a 'torn page'; InnoDB prevents this via the Doublewrite Buffer, writing dirty pages sequentially to a contiguous doublewrite area before flushing them to their actual `.ibd` table positions.

Production Code Example
-- Redo log sizing and durability settings in MySQL 8.0.30+
-- innodb_redo_log_capacity = 4G
-- innodb_doublewrite = ON (only disable on ZFS/hardware guaranteed atomic 16KB writes)
Common Interview Trap / Anti-Pattern:

Confusing Redo Log and Undo Log: Redo Log is physical (page/offset changes) for crash durability (roll-forward), whereas Undo Log is logical (inverse operations) for transaction rollback and MVCC snapshots.

Question #10AdvancedSenior

How do Redo Log and Binary Log (Binlog) coordinate via Two-Phase Commit (2PC), and what do innodb_flush_log_at_trx_commit and sync_binlog control?

Senior Engineering Answer

InnoDB uses the Redo Log for storage-engine crash recovery, while the MySQL server layer writes the Binary Log (`binlog`) for replication and point-in-time recovery. To keep them consistent on a crash, MySQL executes internal Two-Phase Commit: (1) InnoDB prepares the transaction and flushes Redo Log (`PREPARE` state), (2) server writes and fsyncs the Binlog, and (3) InnoDB writes the commit marker to the Redo Log. Setting `innodb_flush_log_at_trx_commit = 1` and `sync_binlog = 1` ('double-1') guarantees zero data loss on OS crash by fsyncing both logs on every commit; relaxing either to `0` or `2` trades up to 1 second of durability for higher write IOPS.

Production Code Example
-- Strict ACID + replication-safe durability settings:
SET GLOBAL innodb_flush_log_at_trx_commit = 1;
SET GLOBAL sync_binlog = 1;
Common Interview Trap / Anti-Pattern:

Setting `innodb_flush_log_at_trx_commit = 2` or `sync_binlog = 0` without realizing an abrupt host power loss can leave the primary out of sync with its replicas (binlog missing committed transactions or vice versa).

Question #11AdvancedSenior

Compare Asynchronous, Semi-Synchronous, and Group Replication in MySQL, and how GTIDs simplify failover.

Senior Engineering Answer

In Asynchronous replication, the primary commits without waiting for replicas—fast, but committed transactions not yet shipped are lost if the primary dies permanently. In Semi-Synchronous replication (e.g., `rpl_semi_sync_master_wait_point = AFTER_SYNC`), the primary waits until at least one replica acknowledges writing the binlog event to its relay log before returning commit success to the client, preventing data loss. Group Replication (used by InnoDB Cluster) uses a Paxos-based consensus protocol across nodes for automatic failover and strong consistency. GTIDs (`server_uuid:transaction_no`) replace fragile file+byte-offset coordinates so replicas automatically locate the exact resume point across any promoted topology.

Production Code Example
-- Always use ROW-based binlog format + GTIDs in modern MySQL replication
-- binlog_format = ROW
-- gtid_mode = ON
-- enforce_gtid_consistency = ON
Common Interview Trap / Anti-Pattern:

Using `STATEMENT`-based binlog replication in production: non-deterministic functions (`UUID()`, `NOW()` in triggers, `LIMIT` without `ORDER BY`) cause silent data drift between primary and replicas.

Question #12AdvancedSenior

Why does MySQL replication lag happen, and how do LOGICAL_CLOCK and WRITESET parallel replication fix it?

Senior Engineering Answer

Replicas receive binlog events from the primary's single I/O thread and apply them via SQL applier threads. Lag occurs when a primary commits concurrent transactions across dozens of connections, but a single-threaded replica applies them serially—or when a huge single DML (`DELETE FROM events WHERE old` modifying 10M rows) blocks the relay log applier, or a replica lacks an index under `ROW` format. MySQL 8.0 solves single-thread bottlenecks via `replica_parallel_type = LOGICAL_CLOCK` combined with `binlog_transaction_dependency_tracking = WRITESET` (tracking row-hash conflicts rather than just commit-group windows), allowing non-conflicting transactions to apply concurrently across `replica_parallel_workers`.

Production Code Example
-- Enable writeset-based parallel replication for maximum replica throughput
SET GLOBAL replica_parallel_type = 'LOGICAL_CLOCK';
SET GLOBAL replica_parallel_workers = 16;
SET GLOBAL binlog_transaction_dependency_tracking = 'WRITESET';
Common Interview Trap / Anti-Pattern:

Replicating tables without a Primary Key in `binlog_format = ROW`: the replica has to perform a full table scan for EVERY single updated or deleted row in the batch!

Question #13StaffPrincipal / Staff

Why do random UUIDv4 Primary Keys hurt InnoDB write throughput, and how do UUIDv7 or ordered binary keys fix it?

Senior Engineering Answer

Because InnoDB clusters table rows inside the Primary Key B+ Tree, sequential keys (`AUTO_INCREMENT` or time-ordered UUIDv7) append new rows cleanly to the rightmost leaf page—keeping hot pages in the Buffer Pool and maintaining ~90%+ page fill factor. Random UUIDv4 keys scatter inserts across the entire B+ Tree: target leaf pages frequently miss the Buffer Pool (causing random disk reads before write), trigger frequent 50% page splits (leaving half-empty fragmented pages), and inflate secondary indexes if stored as 36-byte `CHAR(36)` strings instead of `BINARY(16)`.

Production Code Example
-- Store ordered UUIDv7 (or swapped time-first UUIDv1 via UUID_TO_BIN(uuid, 1)) in BINARY(16)
CREATE TABLE invoices (
    id BINARY(16) NOT NULL PRIMARY KEY,
    account_id BIGINT NOT NULL
) ENGINE=InnoDB;
Common Interview Trap / Anti-Pattern:

Keeping `CHAR(36) CHARSET utf8mb4` as a PK on a 500M-row table with 4 secondary indexes: each row wastes over 500 bytes across indexes compared to `BINARY(16)` or `BIGINT`.

Question #14StaffPrincipal / Staff

How do InnoDB Deadlocks get detected and resolved, and how do you analyze SHOW ENGINE INNODB STATUS output?

Senior Engineering Answer

By default (`innodb_deadlock_detect = ON`), InnoDB runs a wait-for graph cycle check whenever a transaction blocks on a row lock; upon detecting a cycle, InnoDB immediately rolls back the transaction that modified fewer rows (smallest undo log weight) with error 1213 (`Deadlock found when trying to get lock`). Under extreme concurrency where thousands of threads contend on a single hot row, deadlock detection itself can consume 100% CPU traversing huge wait-for graphs—in those cases, teams disable `innodb_deadlock_detect` and rely on a short `innodb_lock_wait_timeout` (e.g., 2s). `SHOW ENGINE INNODB STATUS` prints the `LATEST DETECTED DEADLOCK` section showing the exact two SQL statements, locked index names, and held vs waiting lock modes (`X`, `S`, `gap`).

Production Code Example
-- Enable logging ALL deadlocks (not just the latest) to the MySQL error log during debugging
SET GLOBAL innodb_print_all_deadlocks = ON;
Common Interview Trap / Anti-Pattern:

Assuming an `INSERT ... ON DUPLICATE KEY UPDATE` across concurrent threads cannot deadlock: it acquires gap/insert-intention and S/X locks across unique indexes, making deadlocks common if batch inserts aren't pre-sorted by key.

Question #15StaffPrincipal / Staff

How do MySQL connection scaling limits, thread_cache_size, and external pooling (ProxySQL) behave under high traffic?

Senior Engineering Answer

Community MySQL uses a one-thread-per-connection architecture (unlike thread-pool plugins). Each open connection allocates per-thread buffers (`sort_buffer_size`, `join_buffer_size`, `read_buffer_size`) and adds OS scheduler/mutex contention inside InnoDB's internal lock/trx-sys structures once hundreds of threads run active queries concurrently. Raising `max_connections` to 10,000 without pooling triggers severe latency collapse under load bursts. Production architectures keep `thread_cache_size` tuned to avoid `pthread_create` churn, cap per-app pools via HikariCP/ProxySQL connection multiplexing, and keep active concurrent InnoDB threads bounded.

Production Code Example
-- Inspect thread creation churn vs cached threads
SHOW GLOBAL STATUS LIKE 'Threads_%';
-- High Threads_created indicates thread_cache_size is too small or clients aren't pooling
Common Interview Trap / Anti-Pattern:

Setting `sort_buffer_size` or `join_buffer_size` globally to 64MB+: these buffers are allocated per-connection per-sort/join operation, quickly causing OOM kills under concurrent queries.

Question #16StaffPrincipal / Staff

How do you diagnose and resolve a sudden MySQL production latency spike (CPU saturation vs I/O stall vs lock pileup)?

Senior Engineering Answer

Triage systematically using `SHOW FULL PROCESSLIST` or `performance_schema.threads` + `sys.innodb_lock_waits`: (1) If dozens of queries sit in `Waiting for table metadata lock`, a pending DDL is blocked by an idle/long transaction—kill the blocking idle session; (2) If queries pile up in `Sending data` / `executing` with 100% CPU, inspect `performance_schema.events_statements_summary_by_digest` or the Slow Query Log (`long_query_time = 0.1`, `log_queries_not_using_indexes`) for a plan flip (e.g., stale stats fixed via `ANALYZE TABLE`, or missing index); (3) If CPU is low/iowait is high, check Buffer Pool dirty page flushing, redo log checkpoint age, or disk IOPS throttling.

Production Code Example
-- Find the exact root-cause blocker of lock/MDL pileups in MySQL 8:
SELECT * FROM sys.innodb_lock_waits\G
SELECT * FROM performance_schema.metadata_locks WHERE LOCK_STATUS = 'PENDING';
Common Interview Trap / Anti-Pattern:

Killing random slow queries in `PROCESSLIST` blindly before identifying the head blocker: killing a victim query rolls back its undo log (which can saturate I/O even further if it modified millions of rows) while the actual idle blocker keeps holding the lock.

MySQL Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This MySQL preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Databases & Storage.

JuniorFundamental

How does the InnoDB Clustered Index differ from a Secondary Index, and what is a bookmark lookup?

JuniorFundamental

What are the key differences between InnoDB and MyISAM, and why is utf8mb4 mandatory instead of utf8 in MySQL?

JuniorFundamental

How do CHAR vs VARCHAR and INT(11) vs BIGINT behave in MySQL storage and display?

JuniorFundamental

How do you interpret the key columns of MySQL EXPLAIN (type, key, rows, Extra) and EXPLAIN ANALYZE?

Mid-LevelIntermediate

How does InnoDB implement MVCC using hidden row columns, Undo Logs, and Read Views?

Mid-LevelIntermediate

Explain InnoDB Record Locks, Gap Locks, and Next-Key Locks, and how they prevent phantom reads under Repeatable Read.

Frequently Asked Technical Interview Questions (MySQL)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

How does InnoDB implement MVCC with Undo Logs and Read Views?
InnoDB stamps every row with hidden DB_TRX_ID and DB_ROLL_PTR columns. Updates write prior row images to the Undo Log, and consistent SELECT queries evaluate a Read View snapshot by walking the DB_ROLL_PTR chain back to the latest committed version visible to that transaction.
What is the difference between a Clustered Index and a Secondary Index in InnoDB?
The Clustered Index IS the table, storing complete row data directly in the leaf nodes of the Primary Key B+ Tree. Secondary indexes store only indexed columns plus the Primary Key, requiring a second Clustered Index lookup unless the secondary index covers all selected columns.
What is the InnoDB Doublewrite Buffer and why is it needed?
Because InnoDB pages are 16KB while OS filesystems write 4KB blocks, a crash mid-flush can leave a torn, corrupted page. InnoDB writes pages sequentially to the Doublewrite Buffer before flushing to data files so crash recovery can restore intact pages before replaying redo logs.
How does Semi-Synchronous Replication differ from Asynchronous Replication in MySQL?
Asynchronous replication returns commit success immediately before replicas receive binlog events, risking data loss if the primary fails. Semi-synchronous replication blocks commit completion until at least one replica confirms writing the transaction to its relay log.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks