Skip to content
RED SAGSkills

MySQL interview questions and answers

MySQL questions cover how the database stores, indexes and locks data. Interviewers often ask about InnoDB behaviour, index choice and why a query is slow.

Below are 40 MySQL questions with the correct answer and a short explanation, grouped from fresher to experienced level. Try each one before you open the answer.

What MySQL interviews usually check

  • ✓InnoDB storage, primary keys and clustered indexes
  • ✓Indexes, EXPLAIN and slow queries
  • ✓Transactions, isolation levels and locking
  • ✓Replication and backups
  • ✓Data types, collations and common gotchas

MySQL interview questions for freshers easy

1. Column type for prices

Which column type is best for storing invoice amounts like 1499.99 in PostgreSQL or MySQL?

  1. A.FLOAT with 2 decimal places
  2. B.DOUBLE PRECISION, rounded
  3. C.DECIMAL(12, 2) or NUMERIC
  4. D.REAL, the 4-byte float type
Show answer

Answer: C. DECIMAL(12, 2) or NUMERIC

DECIMAL and NUMERIC store exact decimal values, so sums and tax calculations do not drift. FLOAT, REAL and DOUBLE are binary floating point and cannot represent many decimal amounts exactly. Storing integer paise in a BIGINT is another good option.

2. Why InnoDB over MyISAM

Why is InnoDB the default and recommended MySQL storage engine instead of MyISAM?

  1. A.MyISAM does not support indexes
  2. B.InnoDB supports transactions, row-level locking and crash recovery
  3. C.InnoDB stores data only in memory
  4. D.MyISAM cannot store text columns
Show answer

Answer: B. InnoDB supports transactions, row-level locking and crash recovery

InnoDB is transactional, uses row-level locks and MVCC for concurrency, supports foreign keys and recovers from crashes using its redo log. MyISAM uses table-level locks, has no transactions and can be left corrupted after a crash. That is why modern MySQL uses InnoDB for almost everything.

3. How InnoDB stores table rows

In MySQL with the InnoDB engine, how are the rows of a table physically organised?

  1. A.In a separate heap file in insert order
  2. B.In a hash table keyed by the first column
  3. C.Inside the primary key B-tree, in primary key order
  4. D.In the order of the most used secondary index
Show answer

Answer: C. Inside the primary key B-tree, in primary key order

InnoDB uses a clustered index: the leaf pages of the primary key B-tree hold the full rows. That is why primary key lookups and range scans are fast, and why the choice of primary key affects insert speed and table size.

4. What an InnoDB secondary index points to

In InnoDB, a secondary index on email finds a matching entry. What does that entry contain to reach the full row?

  1. A.The physical disk address of the row
  2. B.The primary key value of the row
  3. C.A copy of every column of the row
  4. D.A hash of the row used for lookup
Show answer

Answer: B. The primary key value of the row

InnoDB secondary index leaves store the indexed columns plus the primary key. To fetch other columns, InnoDB does a second lookup in the clustered (primary key) index. This is why a wide primary key makes every secondary index bigger.

5. Where is the MySQL query cache

An old tuning guide tells you to raise query_cache_size on MySQL 8.4. What should you know?

  1. A.The query cache was removed in MySQL 8.0
  2. B.It must be set to 70% of RAM on 8.4
  3. C.It only works with the MyISAM engine
  4. D.It is renamed to innodb_query_cache
Show answer

Answer: A. The query cache was removed in MySQL 8.0

MySQL removed the query cache in 8.0 because it scaled badly with concurrent writes and caused lock contention. Caching results now belongs in the application or a cache such as Redis, and the InnoDB buffer pool caches data pages.

6. Sizing the InnoDB buffer pool

A dedicated MySQL server has 64 GB RAM and runs only InnoDB. What is a common starting value for innodb_buffer_pool_size?

  1. A.About 4 GB, so the OS cache does the work
  2. B.All 64 GB, so nothing is left unused
  3. C.About 1 GB, the size of the redo log
  4. D.About 45 to 50 GB, roughly 70 to 80% of RAM
Show answer

Answer: D. About 45 to 50 GB, roughly 70 to 80% of RAM

InnoDB caches data and index pages in its buffer pool and uses direct I/O in most setups, so it should get most of the memory on a dedicated host. Leaving 20 to 30% covers connections, the OS and other buffers. Setting it to all RAM risks swapping or the OOM killer.

7. Same MySQL user, different host

In MySQL, 'app'@'10.0.1.%' and 'app'@'localhost' both exist. What does that mean?

  1. A.They are one account with two allowed hosts
  2. B.The localhost entry is ignored when a wildcard exists
  3. C.They are two separate accounts with separate privileges
  4. D.MySQL merges them into one account on restart
Show answer

Answer: C. They are two separate accounts with separate privileges

A MySQL account is identified by both user name and host, so these are two different accounts that can have different passwords and grants. When a client connects, MySQL picks the most specific matching host. This often explains "access denied" for a user that seems to exist.

8. Where to move from MySQL 8.0

MySQL 8.0 reached end of life in April 2026. Your production servers still run 8.0. What is the usual upgrade target for stable production?

  1. A.MySQL 8.4 LTS
  2. B.MySQL 5.7
  3. C.The newest Innovation release, changed every quarter
  4. D.MySQL 8.0 with the query cache turned on
Show answer

Answer: A. MySQL 8.4 LTS

MySQL now has Long-Term Support releases, with 8.4 as the LTS line after 8.0, and short-lived Innovation releases for newer features. Production systems usually follow LTS for longer support. 5.7 is already end of life.

9. Binary logs filling the disk

MySQL binary logs are using 900 GB. Your backups and replicas only need the last 3 days. Which setting controls automatic removal?

  1. A.innodb_log_file_size
  2. B.max_binlog_cache_size
  3. C.binlog_expire_logs_seconds
  4. D.sync_binlog
Show answer

Answer: C. binlog_expire_logs_seconds

binlog_expire_logs_seconds sets how long binary logs are kept before MySQL purges them automatically; 3 days is 259,200 seconds. Make sure no replica or point-in-time recovery plan still needs the older files. sync_binlog controls how often the binlog is flushed to disk.

10. Granting one set of rights to many MySQL users

On MySQL 8.4 you have 30 report users who need the same SELECT grants. What is the cleanest way to manage this?

  1. A.Grant the privileges to a role, and the role to users
  2. B.Copy the mysql.user rows by hand for each user
  3. C.Give every one of the users the SUPER privilege
  4. D.Share one account and one password among all 30
Show answer

Answer: A. Grant the privileges to a role, and the role to users

MySQL 8.0 added roles, which are named bundles of privileges. Grant the role to each user and set it as a default role so it is active at login. Changing the role then changes access for everyone at once.

11. Statements without BEGIN

In psql or a default MySQL session, you run two UPDATE statements without BEGIN. The second fails. What happened to the first?

  1. A.It is rolled back along with the second
  2. B.It waits until you type COMMIT
  3. C.It is already committed on its own
  4. D.It is saved only in the session cache
Show answer

Answer: C. It is already committed on its own

In autocommit mode, every statement outside an explicit transaction is its own transaction and commits when it succeeds. So the first UPDATE stays even though the second failed. Use BEGIN ... COMMIT when several statements must succeed or fail together.

12. DDL in a MySQL transaction

In MySQL you run START TRANSACTION; INSERT INTO a ...; ALTER TABLE b ADD COLUMN c INT; ROLLBACK. What happens to the INSERT?

  1. A.It is rolled back with the ALTER
  2. B.It is rolled back but the ALTER stays
  3. C.It stays; the ALTER committed it implicitly
  4. D.Both fail because DDL is not allowed
Show answer

Answer: C. It stays; the ALTER committed it implicitly

In MySQL, most DDL statements cause an implicit commit before they run, so the INSERT is committed and ROLLBACK has nothing to undo. MySQL 8.0 DDL is atomic on its own, but it is not part of your transaction. Run migrations knowing each DDL commits.

13. When row locks are released

In PostgreSQL and MySQL InnoDB, when are row locks taken by UPDATE released?

  1. A.When the transaction commits or rolls back
  2. B.When the UPDATE statement finishes
  3. C.After deadlock_timeout passes
  4. D.When the next SELECT runs
Show answer

Answer: A. When the transaction commits or rolls back

Both databases use strict two-phase locking for writes: locks are held until the transaction ends. Releasing earlier could let others see or change data that might still be rolled back. That is why long transactions cause long waits.

14. Window functions in MySQL

A team on MySQL 5.7 gets a syntax error on ROW_NUMBER() OVER (...). What is the reason?

  1. A.Window functions arrived in MySQL 8.0
  2. B.MySQL needs the keyword WINDOW before OVER
  3. C.ROW_NUMBER only works inside stored procedures
  4. D.MySQL only allows RANK, not ROW_NUMBER
Show answer

Answer: A. Window functions arrived in MySQL 8.0

MySQL added window functions in version 8.0, and 5.7 has reached end of life. Old workarounds used user variables, which are fragile. Upgrading is the real fix; PostgreSQL, SQL Server, SQLite 3.25+ and the cloud warehouses all support them.

MySQL intermediate interview questions medium

15. Why GTIDs ease MySQL failover

Why do teams enable GTID-based replication in MySQL before setting up automated failover?

  1. A.Replicas find their position by transaction ID
  2. B.GTIDs make replication synchronous
  3. C.GTIDs remove the need for a binary log
  4. D.GTIDs let replicas accept writes
Show answer

Answer: A. Replicas find their position by transaction ID

Each transaction gets a global ID, and with SOURCE_AUTO_POSITION a replica tells the new source which transactions it has, so it can resume without hunting for binlog file names and offsets. This makes repointing replicas after failover simple and safe.

16. MySQL replica lags under heavy writes

A MySQL 8.4 replica lags further behind during busy hours, though its disks are not saturated and CPU is mostly idle. What setting helps it apply changes faster?

  1. A.innodb_buffer_pool_size = 1G
  2. B.binlog_expire_logs_seconds = 0
  3. C.replica_parallel_workers greater than 1
  4. D.sync_binlog = 1000 on the source
Show answer

Answer: C. replica_parallel_workers greater than 1

A single SQL applier thread can fall behind a source that commits many transactions in parallel. Multi-threaded replication applies independent transactions at once, using write-set dependency tracking to keep order safe. In 8.4 it is on by default with 4 workers, and you can tune it upward.

17. Fast new MySQL replica

You need a new MySQL 8.4 replica of a 2 TB source quickly, without setting up a separate backup tool. What is built in for this?

  1. A.mysqldump with --no-data
  2. B.The clone plugin (CLONE INSTANCE FROM)
  3. C.OPTIMIZE TABLE on the source
  4. D.FLUSH TABLES WITH READ LOCK only
Show answer

Answer: B. The clone plugin (CLONE INSTANCE FROM)

The clone plugin copies a physical snapshot of InnoDB data from a donor over the network while it keeps running, then the new instance restarts with the data. With GTIDs, the replica then starts replication from the right position. mysqldump --no-data copies only the schema.

18. Phone number compared to a number

In MySQL, users.phone is VARCHAR(15) with an index. The query WHERE phone = 9876543210 (no quotes) scans the whole table. Why?

  1. A.Indexes on VARCHAR columns can only be used with LIKE patterns
  2. B.Each phone value is converted to a number, so the index is unusable
  3. C.Numbers longer than 9 digits cannot be compared with strings
  4. D.The index is too big to fit in the InnoDB buffer pool
Show answer

Answer: B. Each phone value is converted to a number, so the index is unusable

When a string column is compared with a number, MySQL converts the column values to numbers for the comparison. Many strings can convert to the same number, so the index cannot be used for the lookup. Quote the value so both sides are strings.

19. "Using filesort" in MySQL EXPLAIN

MySQL EXPLAIN shows "Using filesort" in the Extra column of a slow report. What does it mean?

  1. A.The result set is being written out to a CSV file
  2. B.The table data is stored as one file per table
  3. C.Rows are sorted in an extra step, not read in index order
  4. D.MySQL is re-sorting the index files on disk
Show answer

Answer: C. Rows are sorted in an extra step, not read in index order

Filesort is MySQL's name for any sort step, in memory or on disk. It appears when no index provides rows in the ORDER BY order. An index whose columns match the WHERE equality columns followed by the ORDER BY columns can remove it.

20. Hard-coding FORCE INDEX

A developer adds FORCE INDEX (idx_created) to a MySQL query to fix one slow day. What is the main long-term risk?

  1. A.The plan cannot adapt as data changes, and breaks on index renames
  2. B.FORCE INDEX disables the InnoDB buffer pool for that query
  3. C.FORCE INDEX makes the query run in a separate new transaction
  4. D.FORCE INDEX copies the entire table into memory first
Show answer

Answer: A. The plan cannot adapt as data changes, and breaks on index renames

Hints lock in a choice that was right for today's data. As data grows or skews, a different plan may become better and the optimizer cannot choose it. Prefer fixing statistics or indexes, and if you must hint, document and review it.

21. Jumping from MySQL 5.7 to 8.4

A company still on MySQL 5.7 wants to move straight to 8.4 LTS with an in-place upgrade. What does MySQL support?

  1. A.A direct in-place jump from 5.7 to 8.4
  2. B.Only a move to MariaDB first
  3. C.Only upgrades within the 5.7 series
  4. D.Upgrade to 8.0 first, then to 8.4
Show answer

Answer: D. Upgrade to 8.0 first, then to 8.4

MySQL supports in-place upgrades from one LTS or series to the next, so 5.7 must go to 8.0 before 8.4. Skipping a series is not supported for in-place upgrades. A logical dump and load is the other route, and MySQL Shell's upgrade checker helps at each step.

22. Foreign keys and indexes in InnoDB

You add a foreign key in MySQL InnoDB on a child column that has no index. What happens?

  1. A.InnoDB creates an index on the child column automatically
  2. B.The statement fails until you create the index yourself
  3. C.The foreign key works with a full scan on each check
  4. D.InnoDB converts the child table to MyISAM
Show answer

Answer: A. InnoDB creates an index on the child column automatically

InnoDB needs an index on foreign key columns so checks and cascades are fast, and it creates one automatically if none exists. PostgreSQL does not do this, which is a common source of slow deletes there. Naming your own index keeps schema changes predictable.

23. Data silently cut in MySQL

An old MySQL server truncates long strings and turns bad dates into 0000-00-00 with only a warning. Which setting makes these errors instead?

  1. A.Set autocommit = 0
  2. B.Set innodb_strict_mode = OFF
  3. C.Include STRICT_TRANS_TABLES in sql_mode
  4. D.Use character_set_server = latin1
Show answer

Answer: C. Include STRICT_TRANS_TABLES in sql_mode

Without strict mode, MySQL adjusts invalid values and only raises warnings, which hides bugs and bad data. STRICT_TRANS_TABLES, part of the default sql_mode since 5.7, makes the statement fail. Test apps before enabling it on an old system.

24. Reading type=ALL in MySQL EXPLAIN

MySQL EXPLAIN for a slow query shows type: ALL, key: NULL and rows: 48000000 for the orders table. What does it mean?

  1. A.All indexes were used together
  2. B.The query was served from the cache
  3. C.A full table scan with no index used
  4. D.Every row was locked for update
Show answer

Answer: C. A full table scan with no index used

type ALL is the worst access type: MySQL reads every row because no usable index applies. key NULL confirms no index was chosen. Look at the WHERE and JOIN columns and add a suitable index, or rewrite conditions that hide the column.

25. Avoiding double caching in MySQL

A Linux MySQL server caches data both in the InnoDB buffer pool and in the OS page cache. Which setting avoids this double buffering?

  1. A.innodb_flush_log_at_trx_commit = 0
  2. B.sync_binlog = 0
  3. C.innodb_flush_method = O_DIRECT
  4. D.innodb_doublewrite = OFF
Show answer

Answer: C. innodb_flush_method = O_DIRECT

O_DIRECT makes InnoDB bypass the OS cache for data files, so memory is not spent on two copies of the same pages, and the buffer pool can be larger. It is the default on Linux in MySQL 8.4. The other options trade away durability or crash safety.

26. App gets deadlock detected

The app receives "deadlock detected" (PostgreSQL 40P01) or MySQL error 1213. What should the code do?

  1. A.Retry the whole transaction from the start
  2. B.Ignore it, since the other side committed both
  3. C.Restart the database server
  4. D.Increase deadlock_timeout to 1 hour
Show answer

Answer: A. Retry the whole transaction from the start

The database broke the cycle by aborting one transaction, so its work is gone and must be redone from the start. A retry usually succeeds. If deadlocks are frequent, make transactions lock rows in a consistent order and keep them short.

27. Taking a MySQL snapshot at start

In MySQL InnoDB, how do you make the read snapshot start at the beginning of the transaction rather than at the first read?

  1. A.SET autocommit = 1
  2. B.LOCK TABLES ... READ
  3. C.SELECT ... FOR UPDATE on every table
  4. D.START TRANSACTION WITH CONSISTENT SNAPSHOT
Show answer

Answer: D. START TRANSACTION WITH CONSISTENT SNAPSHOT

At Repeatable Read, InnoDB normally creates its read view at the first consistent read. WITH CONSISTENT SNAPSHOT creates it immediately, which tools like mysqldump --single-transaction use so every table is read as of one moment.

28. LOCK TABLES in a transaction

In MySQL a session has an open transaction with inserts, then runs LOCK TABLES orders WRITE. What happens to the open transaction?

  1. A.It is rolled back
  2. B.It continues with the table lock added
  3. C.It is committed implicitly
  4. D.LOCK TABLES fails with an error
Show answer

Answer: C. It is committed implicitly

LOCK TABLES implicitly commits any active transaction before taking the locks. Code that mixes LOCK TABLES with transactions can therefore commit earlier than planned. With InnoDB, row locks inside transactions are usually the better tool.

MySQL interview questions for experienced candidates hard

29. Emoji in reviews fail to save

Reviews containing emoji fail with 'Incorrect string value' in MySQL. The column charset is utf8. What is the fix?

  1. A.Strip all non-English characters first
  2. B.Use utf8mb4; MySQL's utf8 has only 3 bytes
  3. C.Store reviews as BLOBs and decode on read
  4. D.Change the column's charset to latin1
Show answer

Answer: B. Use utf8mb4; MySQL's utf8 has only 3 bytes

In MySQL, utf8 is an alias for utf8mb3, which only covers characters up to 3 bytes. Emoji and some rare scripts need 4 bytes. Convert the database, tables, columns and connection to utf8mb4. latin1 cannot store Arabic or Hindi at all.

30. InnoDB gap locks

In MySQL InnoDB at the default REPEATABLE READ level, session A runs SELECT * FROM t WHERE id BETWEEN 10 AND 20 FOR UPDATE inside a transaction. Session B tries INSERT INTO t (id) VALUES (15), and no row with id 15 exists. What happens?

  1. A.The insert succeeds at once because id 15 was not locked
  2. B.The insert waits, because InnoDB took next-key (gap) locks on the range to prevent phantoms
  3. C.The insert succeeds but session A gets a dirty read error
  4. D.MySQL raises a duplicate key error
Show answer

Answer: B. The insert waits, because InnoDB took next-key (gap) locks on the range to prevent phantoms

For locking reads on a range, InnoDB REPEATABLE READ uses next-key locks, which lock index records and the gaps between them. This blocks inserts into the range so the locking read cannot see phantom rows. It is a common, surprising source of lock waits and deadlocks; READ COMMITTED mostly disables gap locking.

31. Faster commits with a durability cost

A team sets innodb_flush_log_at_trx_commit = 2 to speed up writes. What is the real risk?

  1. A.Data can be lost if mysqld itself crashes, but never on a power failure
  2. B.Transactions are no longer atomic
  3. C.Up to about one second of committed transactions can be lost if the OS crashes or power fails, because the log is written to the OS cache at commit but flushed to disk only once a second
  4. D.There is no risk; it only changes logging verbosity
Show answer

Answer: C. Up to about one second of committed transactions can be lost if the OS crashes or power fails, because the log is written to the OS cache at commit but flushed to disk only once a second

With value 1 the redo log is written and fsynced at every commit, giving full durability. With 2 it is written to the OS at commit, so a mysqld crash loses nothing, but an OS crash or power loss can lose about the last second. With 0 even a mysqld crash can lose data. Pair the choice with sync_binlog when replication consistency matters.

32. Where old row versions are kept

How do PostgreSQL and MySQL InnoDB differ in storing old row versions for MVCC?

  1. A.Both keep old versions only in the WAL or redo log
  2. B.PostgreSQL keeps them in the table; InnoDB updates in place and keeps undo
  3. C.PostgreSQL uses undo logs; InnoDB writes new rows in the table
  4. D.Neither keeps old versions; both lock rows for every read
Show answer

Answer: B. PostgreSQL keeps them in the table; InnoDB updates in place and keeps undo

PostgreSQL writes a new tuple per update and leaves the old one in the heap until VACUUM removes it, which is why bloat happens. InnoDB changes the row in place and writes the old version to undo logs, which purge cleans. Both give readers snapshots without read locks.

33. MySQL ignores an index on phone

In MySQL, phone is a VARCHAR column with an index. The query below does a full table scan. Why?

SELECT * FROM customers WHERE phone = 9876543210;
  1. A.Comparing text to a number converts every row
  2. B.VARCHAR columns cannot have B-tree indexes
  3. C.The index is only used with ORDER BY
  4. D.Numbers must be compared with LIKE
Show answer

Answer: A. Comparing text to a number converts every row

When a string column is compared with a numeric literal, MySQL converts the column value of every row to a number, so the index cannot be used and the results can match odd values like '9876543210abc'. Quote the value: WHERE phone = '9876543210'.

34. Top queries without a slow log

The MySQL slow log is off and you cannot restart. Where can you see which statements use the most total time since startup?

  1. A.information_schema.TABLES
  2. B.SHOW PROCESSLIST
  3. C.mysql.user
  4. D.The sys.statement_analysis view
Show answer

Answer: D. The sys.statement_analysis view

performance_schema aggregates statement digests with counts, total latency and rows examined, and the sys schema shows them in readable views such as statement_analysis. SHOW PROCESSLIST shows only what is running now. information_schema.TABLES has table sizes, not query costs.

35. Old replication commands fail on 8.4

A failover script runs CHANGE MASTER TO and SHOW SLAVE STATUS against MySQL 8.4 and gets syntax errors. Why?

  1. A.They were removed; use the SOURCE/REPLICA forms
  2. B.Replication is not supported on MySQL 8.4
  3. C.They now need the SUPER privilege first
  4. D.They work only over the X Protocol port
Show answer

Answer: A. They were removed; use the SOURCE/REPLICA forms

MySQL 8.0.22 introduced CHANGE REPLICATION SOURCE TO, SHOW REPLICA STATUS and START REPLICA, and 8.4 removed the old MASTER and SLAVE forms. Scripts and monitoring checks must be updated before upgrading. Output column names changed too, such as Source_Host.

36. SELECT and SELECT FOR UPDATE disagree

In MySQL InnoDB at Repeatable Read, a transaction reads stock = 10 with a plain SELECT. Another transaction commits stock = 4. The first then runs SELECT stock ... FOR UPDATE. What does it return?

  1. A.10, because the snapshot is fixed for it
  2. B.An error, as its snapshot is too old
  3. C.4, as locking reads see the latest commit
  4. D.NULL, since the row changed
Show answer

Answer: C. 4, as locking reads see the latest commit

In InnoDB, plain SELECTs use the transaction's consistent snapshot, but locking reads (FOR UPDATE, FOR SHARE) and UPDATE/DELETE read and lock the latest committed version. So the same transaction can see 10 and then 4. Base writes on the locking read, not the earlier snapshot.

37. One UPDATE blocks the whole table

In MySQL InnoDB at Repeatable Read, UPDATE orders SET flag = 1 WHERE note = 'x' runs where note has no index. Other sessions now cannot update any order row. Why?

  1. A.MySQL takes a table lock for every UPDATE
  2. B.The binary log blocks updates until it rotates
  3. C.Unindexed columns turn on SERIALIZABLE mode
  4. D.InnoDB locks every row it scans, which is the whole table
Show answer

Answer: D. InnoDB locks every row it scans, which is the whole table

InnoDB sets locks on the index records it examines, not just the rows that match. Without an index on note, it scans the clustered index and locks every row plus the gaps. Adding an index on the filter column limits locks to matching rows.

38. An idle MySQL session blocks ALTER

A tool connects to MySQL with autocommit = 0, runs one SELECT on orders and sits idle. Later ALTER TABLE orders hangs with "Waiting for table metadata lock". Why?

  1. A.SELECTs take a table write lock in MySQL
  2. B.Its open transaction holds a metadata lock
  3. C.ALTER TABLE always waits for idle sessions
  4. D.The binary log is full
Show answer

Answer: B. Its open transaction holds a metadata lock

With autocommit off, the SELECT started a transaction, and InnoDB keeps a shared metadata lock on every table used until it ends. ALTER needs an exclusive metadata lock, so it waits, and new queries queue behind it. Find the session in performance_schema.metadata_locks and end it.

39. Deadlock from two concurrent inserts

In MySQL at Repeatable Read, two sessions each run SELECT ... FOR UPDATE for a missing id in the same gap, then each INSERT that id range. Both block and one is killed as a deadlock victim. Why?

  1. A.Each holds a gap lock that blocks the other's insert
  2. B.Inserts always deadlock in MySQL
  3. C.FOR UPDATE on a missing row takes a table lock
  4. D.The auto-increment counter deadlocked
Show answer

Answer: A. Each holds a gap lock that blocks the other's insert

A locking read that finds no row still locks the gap. Gap locks from two sessions are compatible, but an insert needs an insert intention lock that conflicts with the other's gap lock, so each waits on the other. Use INSERT ... ON DUPLICATE KEY UPDATE or a unique key with retry instead.

40. REPLACE INTO removed child rows

In MySQL, a sync job runs REPLACE INTO customers (...) for existing customers. Afterwards their orders, linked with ON DELETE CASCADE, are gone. Why?

  1. A.REPLACE truncates the whole table first
  2. B.Cascades run on every UPDATE in MySQL
  3. C.REPLACE turns off all foreign key checks
  4. D.REPLACE deletes the old row and inserts anew
Show answer

Answer: D. REPLACE deletes the old row and inserts anew

When a key already exists, REPLACE deletes the old row and inserts a new one, so delete triggers and ON DELETE CASCADE fire. That wipes children and can also change auto-increment IDs. INSERT ... ON DUPLICATE KEY UPDATE changes the row in place instead.

Ready to test yourself?

Take a 15-question MySQL MCQ test with a score at the end, or practise the full MySQL question bank and earn points on the leaderboard.