MySQL interview questions and answers: InnoDB, locking and replication

MySQL interview questions are mostly InnoDB questions: how the clustered primary key lays out the table, why a secondary index lookup costs two trips, how to read EXPLAIN, and how REPEATABLE READ uses next-key and gap locks. Senior rounds add the binlog and replication lag, online schema changes and classic pitfalls such as utf8 versus utf8mb4. Tie every answer to the storage engine and you will sound like someone who has run MySQL in production.

By Published 10 min read

Where MySQL questions show up

MySQL sits under a huge share of web applications, so it appears in backend interviews for PHP, Ruby, Java, Go and Python stacks, in DBA and SRE loops at companies that run it at scale, and in system design rounds that start from a single primary. Backend interviewers want indexing, EXPLAIN and transaction behavior. DBA interviewers go further into replication topologies, backups, schema changes on large tables and the InnoDB status output.

  1. Phone or online screenDefinitions and quick checks: storage engines, primary versus unique keys, isolation default, charset. Some companies add a short query test.
  2. Technical roundDesign a few tables, choose primary keys and indexes, read an EXPLAIN output, and explain why a query is slow.
  3. Operations or senior roundReplica lag, a deadlock log, a full disk from binlogs, or a migration on a table with hundreds of millions of rows.

InnoDB fundamentals

Questions on the storage engine
QuestionWhat it testsWhat a strong answer shows
Why is InnoDB the default engine, and when did anyone use MyISAM?Engine basicsInnoDB has transactions, row-level locking, foreign keys and crash recovery. MyISAM had table locks and no transactions; it survives mostly in old systems.
What is a clustered index in InnoDB?Physical layoutThe table is the primary key B-tree: leaf pages hold full rows in key order. Without a declared primary key, InnoDB uses the first NOT NULL unique index or creates a hidden row ID.
What does a secondary index store?Lookup costThe indexed columns plus the primary key value. A lookup finds the primary key in the secondary index, then walks the clustered index to fetch the row.
Why do long primary keys hurt?Index sizeEvery secondary index repeats the primary key, so a wide key (a long string, a composite of several columns) inflates all of them.
Auto-increment integer or UUID as the primary key?Insert patternSequential keys append to the right edge of the tree. Random UUIDs insert all over it, causing page splits and a cold buffer pool. If you need UUIDs, store them as BINARY(16) in a time-ordered form.
What is the buffer pool?MemoryInnoDB's cache of data and index pages. On a dedicated server it is usually the largest memory setting, sized so the working set fits.
Redo log, undo log, binlog: what is each for?Logging layersRedo makes committed changes durable for crash recovery. Undo keeps old versions for rollback and consistent reads. The binlog is the server-level change stream for replication and point-in-time recovery.
Why is SELECT COUNT(*) slow on a big InnoDB table?MVCC costThere is no stored row count, because each transaction may see a different number of rows. The engine scans the smallest index it can.
DATETIME or TIMESTAMP?Types and time zonesTIMESTAMP converts from the session time zone to UTC and back, and its range ends in January 2038. DATETIME stores the value as given. Many teams store UTC in DATETIME and convert in the application.
utf8 or utf8mb4?CharsetsIn MySQL, utf8 has meant utf8mb3, at most three bytes per character, so emoji and some CJK characters fail or get mangled. Use utf8mb4.
Questions on the storage engine. Scroll sideways on a small screen.

Index and EXPLAIN questions

  • What is the leftmost prefix rule? An index on (a, b, c) can serve filters on a, on a and b, or on all three. A filter on b alone usually cannot seek, and a range on a stops b from being used for seeking.
  • What is a covering index, and how does EXPLAIN show it? The index contains every column the query reads, including the primary key that every secondary index already carries. Extra shows "Using index" and the clustered index is never touched.
  • What does "Using index condition" mean? Index condition pushdown: the engine filters on later index columns before fetching full rows, which saves clustered index lookups.
  • Using filesort and Using temporary: are they bad? They mean an extra sort or an internal temporary table. Fine on small results, expensive on large ones. An index matching both WHERE and ORDER BY often removes the filesort.
  • What are the most common values of the type column, from best to worst? const and eq_ref (one row by unique key), ref (non-unique equality), range, index (full index scan) and ALL (full table scan).
  • How do you index a long VARCHAR column? A prefix index such as INDEX (url(100)) keeps it small, but it cannot cover the query or enforce uniqueness on the full value.
  • What is an invisible index for? It makes the optimizer ignore an index without dropping it (MySQL 8.0), so you can test whether removing it hurts before paying to rebuild it.
  • EXPLAIN versus EXPLAIN ANALYZE? EXPLAIN shows the chosen plan and estimates. EXPLAIN ANALYZE, added in MySQL 8.0, runs the query and reports actual timings per step in tree form.
  • Why does the optimizer pick a full scan when an index exists? Low selectivity, stale index statistics, a function or type conversion on the column, or a cheaper path through a different index. ANALYZE TABLE refreshes statistics.
CREATE TABLE orders (
  id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  customer_id INT UNSIGNED NOT NULL,
  status      VARCHAR(16) NOT NULL,
  created_at  DATETIME NOT NULL,
  total       DECIMAL(10,2) NOT NULL,
  KEY idx_customer_created (customer_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

EXPLAIN SELECT id, created_at FROM orders
WHERE customer_id = 42 AND created_at >= NOW() - INTERVAL 30 DAY;
-- type: range   key: idx_customer_created   Extra: Using where; Using index

EXPLAIN SELECT * FROM orders WHERE created_at >= NOW() - INTERVAL 1 DAY;
-- type: ALL   key: NULL   (created_at is not the leftmost column)
With 200,000 generated rows, the first query is answered from the secondary index alone (Using index), because the primary key id is stored in every secondary entry. Exact output varies by version, but the idea is the same.

A pitfall interviewers love: comparing a string column with a number. MySQL converts each stored value to a number to compare, so the index cannot be used for a lookup. In a test, WHERE phone = 5551234 scanned the whole phone index (about 50,000 entries), while WHERE phone = '5551234' found one row by key. The fix is to pass the right type from the application.

Transactions, isolation and InnoDB locking

Locking questions that decide senior offers
QuestionWhat it testsWhat a strong answer shows
What is MySQL's default isolation level?DefaultsREPEATABLE READ for InnoDB. Plain SELECTs read from a consistent snapshot taken at the first read, built from undo records.
What is the difference between a consistent read and a locking read?MVCC versus locksA plain SELECT reads the snapshot and takes no row locks. SELECT ... FOR UPDATE or FOR SHARE reads the latest committed version and locks what it scanned.
What is a gap lock?Phantom preventionA lock on the space between index records, so no other transaction can insert into that range. It exists to stop phantoms under REPEATABLE READ.
What is a next-key lock?InnoDB internalsA record lock plus the gap before it. Locking reads and updates under REPEATABLE READ take next-key locks on every index record they scan, not only the matching ones.
Why can an UPDATE with a WHERE on an unindexed column lock the whole table?Scan lockingInnoDB locks every row it examines. With no usable index it scans everything, so every row and gap is locked until commit.
What changes under READ COMMITTED?Trade-offsEach statement gets a fresh snapshot, and gap locking is mostly turned off (it remains for foreign key and duplicate key checks). Fewer deadlocks, but phantoms become possible.
Where do you look after a deadlock?DiagnosticsSHOW ENGINE INNODB STATUS prints the latest detected deadlock with both transactions' statements and locks. InnoDB rolls back one victim with error 1213, and the application should retry it.
What does innodb_lock_wait_timeout control?Waiting versus deadlockHow long a statement waits for a row lock before error 1205 (default 50 seconds). Deadlocks are detected immediately; ordinary waits run to this timeout.
Why do long transactions hurt even if they only read?Purge lagOld snapshots keep undo history alive, so purge falls behind and the history list grows, slowing reads that must walk older versions.
Locking questions that decide senior offers. Scroll sideways on a small screen.
-- seats has rows with id 10 and 20
-- Session A                                 -- Session B
BEGIN;                                       BEGIN;
SELECT * FROM seats WHERE id = 15 FOR UPDATE;
                                             SELECT * FROM seats WHERE id = 16 FOR UPDATE;
INSERT INTO seats VALUES (15, 'tx1');  -- waits
                                             INSERT INTO seats VALUES (16, 'tx2');
                                             -- ERROR 1213: Deadlock found
COMMIT;  -- A's insert succeeds
A classic gap-lock deadlock, reproduced on InnoDB in two sessions. Both locking reads hit the empty gap between 10 and 20, gap locks do not conflict with each other, then each INSERT waits for the other's gap lock. One session gets ERROR 1213.

The fix depends on intent. If the goal is "insert if missing", skip the locking read and let a unique key decide: INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE and check the affected rows. Switching to READ COMMITTED also removes this pattern, but say what you give up.

Replication and high availability

  • How does MySQL replication work? The source writes changes to the binary log. Each replica's I/O thread copies them into a relay log and the SQL (applier) threads replay them.
  • Statement, row or mixed binlog format? Statement-based logs the SQL text and can diverge with non-deterministic statements. Row-based logs changed rows, is safer and is the default in current versions, at the cost of larger logs for bulk updates.
  • What are GTIDs and why do they help? A global transaction ID on every transaction lets a replica know exactly which transactions it has applied, so failover and repointing do not need binlog file names and positions.
  • Asynchronous versus semi-synchronous replication? Asynchronous commits without waiting for replicas, so a crash can lose the tail. Semi-sync waits until at least one replica has received (not applied) the transaction.
  • Why does a replica lag, and how do you measure it? Large transactions, a single-threaded applier, missing indexes on the replica, or heavy reads competing for I/O. Check SHOW REPLICA STATUS (SHOW SLAVE STATUS on older versions) or a heartbeat table, and enable parallel applier threads.
  • How do you avoid stale reads after a write? Read your own writes from the source for a short window, route by session, or wait until the replica has applied the write's GTID.
  • What are Group Replication and InnoDB Cluster? A built-in multi-node replication layer with automatic membership and failover, usually run single-primary, managed with MySQL Shell and fronted by MySQL Router.
  • What do you need for point-in-time recovery? A full backup (logical with mysqldump or physical with a hot-backup tool such as Percona XtraBackup) plus the binlogs since then, replayed up to just before the bad statement.

Schema changes and common pitfalls

Production scenarios and pitfalls
ScenarioLikely causeWhat you would do
An ALTER TABLE left every query on the table "Waiting for table metadata lock".Metadata lock queueThe ALTER waited behind a long transaction, and new queries queued behind the ALTER. Find and end the old transaction; next time set a short lock_wait_timeout for the session.
Adding a column to a 500 million row table.Table rebuild costCheck whether ALGORITHM=INSTANT or INPLACE applies; otherwise use gh-ost or pt-online-schema-change, which copy into a shadow table and swap.
Page 5,000 of a listing endpoint takes seconds.Deep OFFSETLIMIT 20 OFFSET 100000 reads and throws away 100,000 rows. Switch to keyset pagination on (created_at, id).
A unique username check lets "Ana" and "ana" collide.CollationDefault collations are case-insensitive, so the unique index treats them as equal. Decide if that is the rule you want; otherwise use a binary or case-sensitive collation.
A GROUP BY query errors after an upgrade.ONLY_FULL_GROUP_BYWith the ONLY_FULL_GROUP_BY SQL mode on, non-aggregated columns that are not in GROUP BY are rejected. Add them to GROUP BY or wrap them in an aggregate; do not just disable the mode.
Emoji arrive as question marks.utf8mb3 somewhereColumn, table, connection or client charset still utf8. Fix all layers to utf8mb4.
Auto-increment IDs jump by large steps.Normal behaviorRolled-back inserts and INSERT ... ON DUPLICATE KEY UPDATE can consume values. IDs are unique, not gapless.
Production scenarios and pitfalls. Scroll sideways on a small screen.
-- Next page after the last row the client saw
SELECT id, created_at FROM orders
WHERE customer_id = 42
  AND (created_at, id) < ('2026-11-01 00:00:00', 999999)
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- Counter upsert on a composite primary key
CREATE TABLE daily_views (
  page_id INT NOT NULL,
  day     DATE NOT NULL,
  views   INT NOT NULL,
  PRIMARY KEY (page_id, day)
);
INSERT INTO daily_views (page_id, day, views) VALUES (7, '2026-12-03', 1)
  ON DUPLICATE KEY UPDATE views = views + 1;
Keyset pagination and an upsert. The second insert of the same key raised views to 2 instead of failing.

One caution on the keyset query: some MySQL versions handle row-value comparisons like (created_at, id) < (...) less efficiently than the expanded form created_at < ? OR (created_at = ? AND id < ?). Check the plan on your version.

Fictional example

Answering "Checkout throws deadlock errors a few times an hour. What do you do?"
Interviewer
Our checkout service writes to orders and inventory. Since a release last week we get a few deadlock errors per hour. How do you approach it?
Candidate
First I would read the latest deadlock section in SHOW ENGINE INNODB STATUS, or turn on innodb_print_all_deadlocks so every one reaches the error log, because the latest one gets overwritten. That shows both statements and which index and gap each one held. Two shapes are common. One is opposite ordering: one path locks inventory then orders, another orders then inventory. The fix is a single order everywhere. The other is gap locks: a SELECT ... FOR UPDATE on a row that does not exist yet, followed by an insert. That one I would replace with an insert guarded by a unique key. I would also check that the WHERE clauses use an index, since an unindexed update locks every row it scans. Deadlocks never go to zero, so the service should retry error 1213 with a short backoff, and I would chart deadlocks per hour to confirm the fix.

Ten-day MySQL practice plan

  • Days 1 and 2: create tables with integer and UUID primary keys, load a few million rows, and compare table and index sizes with information_schema.
  • Days 3 and 4: write queries that do and do not use the leftmost prefix, then read EXPLAIN and EXPLAIN ANALYZE for each. Make one query covering and watch Extra change.
  • Days 5 and 6: open two clients and reproduce a lock wait, the gap-lock deadlock above and a lost update. Repeat under READ COMMITTED and note what changes.
  • Days 7 and 8: set up a source and a replica with GTIDs, stop the replica, write on the source, and watch it catch up. Practice explaining lag and failover.
  • Days 9 and 10: run an online schema change on a large table with a tool such as gh-ost in a sandbox, then rehearse the pitfall table aloud.

If your stack might be Postgres instead, the PostgreSQL interview questions page covers the heap-and-VACUUM model, which differs from InnoDB at almost every point. Java teams on MySQL usually ask ORM questions too: see Hibernate and JPA interview questions. Caching in front of MySQL is covered in Redis interview questions, and splitting it across machines in database sharding.

Rehearsing these out loud shows quickly where you skip steps. During a mock MySQL round, Natively, an AI interview assistant for Mac and Windows, transcribes the conversation on your machine so you can check later whether you mentioned the index before the fix. While practicing it can take a screenshot of an EXPLAIN table or a deadlock log and suggest what to point out, and with Pro or the free trial it can use the résumé and job description you add. The notes and transcript stay for you to go over afterwards.

Questions people ask

What MySQL questions are asked in interviews?

Most are about InnoDB: the clustered primary key, secondary indexes, reading EXPLAIN, the REPEATABLE READ default with next-key and gap locks, and deadlocks. Senior and DBA rounds add binlog replication, lag, backups and online schema changes.

What is a clustered index in MySQL?

In InnoDB the table itself is a B-tree ordered by the primary key, with full rows in the leaf pages. Secondary indexes store the primary key value and use it to fetch the row, so a short, sequential primary key keeps every index small.

What are gap locks in MySQL?

Locks on the space between index records, taken by locking reads and updates under REPEATABLE READ to stop other transactions inserting phantom rows. They are the usual cause of deadlocks when two sessions lock a missing row and then insert.

How do I prepare for a MySQL DBA interview?

Run a source and a replica locally, practice reading EXPLAIN and SHOW ENGINE INNODB STATUS, reproduce a gap-lock deadlock in two sessions, and rehearse replication lag, point-in-time recovery and online schema change scenarios out loud.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP