PrepStack › Databases › MySQL

MySQL interview cheat sheet

InnoDB internals, MVCC & locking, EXPLAIN, replication, backups and scaling

MySQL rounds go past plain SQL. Interviewers check that you know how InnoDB stores and protects data: the clustered primary key, the buffer pool, redo and undo logs, MVCC and next-key locks. Then they move to operations: reading EXPLAIN, fixing slow queries, replication lag, backups and sharding. Read the 15-minute revision first, then use Quiz mode and answer out loud. MySQL-only snippets are illustrative; snippets with output are portable SQL run in SQLite.

15-minute revision

  1. Layers: connection layer (thread per connection, auth) → SQL layer (parser, optimizer, executor, binlog) → storage engine API → engine (InnoDB by default).
  2. InnoDB = transactions, row locks, MVCC, crash recovery, foreign keys. MyISAM = table locks, no transactions, no crash safety. Use InnoDB.
  3. InnoDB tables are a B+tree on the primary key (the clustered index). Leaf pages hold the full row. Pages are 16 KB by default.
  4. Secondary indexes store the PK value, not a row pointer. A non-covering lookup does two B+tree searches. Keep the PK short.
  5. Prefer a short, increasing PK (BIGINT AUTO_INCREMENT or time-ordered UUID in BINARY(16)). Random UUIDv4 keys cause page splits, fragmentation and cache misses.
  6. Buffer pool caches data and index pages in RAM (LRU with young/old sublists). Size it to roughly 50–75% of RAM on a dedicated server.
  7. Redo log = write-ahead log for durability (replayed after a crash). Undo log = old row versions for rollback and MVCC. Doublewrite protects against torn pages.
  8. Default isolation is REPEATABLE READ. Plain SELECT reads a snapshot (read view); FOR UPDATE/UPDATE/DELETE read the latest rows and take locks.
  9. RR uses next-key locks (record + gap before it) on locking reads to block phantoms. READ COMMITTED mostly drops gap locks.
  10. Deadlocks are detected automatically; InnoDB rolls back the cheaper transaction (error 1213). Read SHOW ENGINE INNODB STATUS → LATEST DETECTED DEADLOCK, then retry in the app.
  11. EXPLAIN type from best to worst: const → eq_ref → ref → range → index → ALL. Watch Extra: Using index good; Using filesort, Using temporary need a look.
  12. Composite indexes follow the leftmost prefix rule. Put equality columns first, then the range or sort column. A range stops later columns from being used for seeking.
  13. Use utf8mb4 (real UTF-8, emoji). utf8 is an alias for 3-byte utf8mb3. TIMESTAMP is stored as UTC and ends in 2038; DATETIME has no time zone and runs to 9999.
  14. Replication ships the binlog (ROW format by default) from source to replicas. Async by default; semi-sync waits for one replica ACK; GTIDs make failover simple.
  15. Backups: mysqldump --single-transaction (logical, small DBs), XtraBackup or MySQL Enterprise Backup (physical, hot). PITR = full backup + replay binlogs up to the bad event.
  16. Versions (Dec 2026): 8.0 reached EOL in April 2026. LTS lines are 8.4 and 9.7. Innovation releases now use calendar versions (26.7, 26.10).

Architecture & versions

MySQL server architecture

A shared SQL layer parses and plans queries, then talks to pluggable storage engines through the handler API.

  • Connection layer: accepts TCP (port 3306) or socket connections, does authentication and TLS, and gives each connection its own thread. thread_cache_size reuses threads; max_connections defaults to 151.
  • SQL layer: the parser builds a parse tree, the resolver checks names and privileges, the cost-based optimizer picks join order and indexes, and the executor runs the plan.
  • The SQL layer also owns the binary log (binlog), so replication works the same for any engine.
  • Storage engine API (the handler interface): calls like 'open table', 'read next row by index', 'write row'. InnoDB implements it; so do MyISAM, MEMORY, CSV and others.
  • Engines are chosen per table (ENGINE=InnoDB). Since 8.0 the data dictionary itself is stored in InnoDB tables, so DDL is atomic and crash-safe.
  • The old query cache was removed in MySQL 8.0. It scaled badly because any write to a table cleared all cached results for that table.

Interview questions

  • Walk me through what happens when MySQL runs a SELECT.
  • What is a storage engine and why is MySQL designed that way?

InnoDB vs MyISAM (and other engines)

InnoDB is the default and right choice: ACID, row locks, MVCC and crash recovery. MyISAM is legacy.

  • InnoDB: transactions, row-level locking, MVCC, foreign keys, crash recovery via redo log, clustered PK.
  • MyISAM: table-level locks, no transactions, no foreign keys, can corrupt on crash and needs REPAIR TABLE. Data (.MYD) and indexes (.MYI) are separate files; indexes point to row offsets.
  • MyISAM stores the exact row count, so SELECT COUNT(*) FROM t (no WHERE) is instant. InnoDB must count rows because each transaction may see a different count.
  • MEMORY: tables in RAM, lost on restart, table locks. CSV, ARCHIVE, BLACKHOLE, FEDERATED are niche.
  • Since 8.0, InnoDB also handles full-text and spatial indexes, so MyISAM has no real advantage left.

Interview questions

  • Difference between InnoDB and MyISAM?
  • Why is COUNT(*) slower on InnoDB than MyISAM?

Versions, release model & what's new

8.0 is end-of-life (April 2026). Run an LTS (8.4 or 9.7); Innovation releases move fast and are supported only until the next one.

  • Since 2023 MySQL has two tracks: LTS releases (long support, only fixes) and Innovation releases (new features roughly every quarter, short support).
  • 8.0 (GA April 2018) brought the transactional data dictionary, atomic DDL, CTEs and window functions, roles, invisible and descending indexes, histograms, SKIP LOCKED/NOWAIT, instant ADD COLUMN, hash join and EXPLAIN ANALYZE. It reached end of life in April 2026.
  • 8.4 LTS (April 2024): mysql_native_password disabled by default, old 'master/slave' syntax removed (SHOW BINARY LOG STATUS, CHANGE REPLICATION SOURCE TO), and new InnoDB defaults (for example adaptive hash index and change buffering off).
  • 9.x Innovation (9.0–9.6): VECTOR data type, mysql_native_password removed, JavaScript stored programs (Enterprise). 9.7 (April 2026) is the next LTS.
  • From July 2026 versions are calendar-based (YY.M): 26.7 and 26.10 are Innovation releases.
  • Default auth plugin since 8.0 is caching_sha2_password; default charset is utf8mb4 with collation utf8mb4_0900_ai_ci.

Interview questions

  • What is the difference between MySQL LTS and Innovation releases?
  • What were the biggest changes in MySQL 8.0?
  • Your company still runs MySQL 8.0. What do you recommend?

InnoDB internals

Clustered index & secondary indexes

An InnoDB table is a B+tree ordered by primary key; every secondary index leaf stores the PK to find the row.

  • The clustered index is the table: leaf pages hold whole rows, sorted by PK. A PK lookup or PK range scan is very fast.
  • If you define no PK, InnoDB uses the first NOT NULL UNIQUE index; otherwise it adds a hidden 6-byte DB_ROW_ID. Since 8.0.30 sql_generate_invisible_primary_key can add an invisible my_row_id column instead.
  • A secondary index leaf stores (indexed columns + PK value). Reading other columns means a second search in the clustered index (a 'bookmark lookup').
  • A covering index contains every column the query needs, so the second lookup is skipped. EXPLAIN shows Using index.
  • Because the PK is copied into every secondary index, a wide PK (long strings, composite keys) makes all indexes bigger.
  • Pages are 16 KB by default (innodb_page_size). Rows that don't fit put long TEXT/BLOB/JSON values in overflow pages.

Interview questions

  • What is a clustered index in InnoDB?
  • Why do InnoDB secondary indexes store the primary key instead of a row pointer?
  • What is a covering index and how do you spot it?
  • What happens if a table has no primary key?

Choosing a primary key: auto-increment vs UUID

Short, increasing keys append to the right edge of the B+tree; random UUIDs insert everywhere and cause page splits.

  • With AUTO_INCREMENT, new rows go to the last leaf page. Pages fill up nearly full and the hot page stays in memory.
  • Random UUIDv4 keys land in random pages. Full pages must split (half the rows move to a new page), pages end up about half full, and inserts need random disk reads once data exceeds the buffer pool.
  • Storing a UUID as CHAR(36) takes 36+ bytes and is copied into every secondary index. Use BINARY(16) with UUID_TO_BIN().
  • UUID_TO_BIN(uuid, 1) swaps the time parts of a version-1 UUID so values become roughly increasing. UUIDv7 (time-ordered) gives the same benefit and can be generated in the app.
  • Auto-increment drawbacks: IDs are guessable, and they need coordination across shards. Common fixes: expose a separate public ID, or use time-ordered IDs (UUIDv7, Snowflake-style).
  • innodb_autoinc_lock_mode = 2 (default since 8.0) allows concurrent inserts; IDs can have gaps after rollbacks or failed inserts. Never rely on IDs being gap-free.

Interview questions

  • Why is a random UUID a bad primary key in InnoDB?
  • How would you use UUIDs and still get good insert performance?
  • Can AUTO_INCREMENT values have gaps? Why?

Buffer pool, change buffer & adaptive hash index

The buffer pool caches pages in RAM; the change buffer delays secondary index updates; the AHI adds hash lookups over hot B+tree pages.

  • The buffer pool caches data and index pages. Reads hit RAM when possible; writes change pages in RAM (making them dirty) and background page cleaners flush them later.
  • It uses an LRU with a midpoint: new pages enter the 'old' sublist (about 3/8, innodb_old_blocks_pct = 37) and move to 'young' only if read again. This stops one big table scan from evicting the hot set.
  • Size with innodb_buffer_pool_size (resizable online). On a dedicated DB host, 50–75% of RAM is typical; innodb_dedicated_server = ON sizes it automatically.
  • The change buffer records changes to non-unique secondary index pages that aren't in memory and merges them later, saving random reads. Unique indexes can't use it because they must check for duplicates right away.
  • The adaptive hash index (AHI) builds an in-memory hash over frequently searched B+tree pages, so some lookups skip the tree walk. It can become a contention point on write-heavy loads.
  • In 8.4 LTS both innodb_adaptive_hash_index and innodb_change_buffering default to off; on 8.0 they were on.

Interview questions

  • What is the InnoDB buffer pool and how do you size it?
  • Why doesn't a full table scan wipe out the buffer pool?
  • What is the change buffer and why can't unique indexes use it?

Redo log, undo log, doublewrite & crash recovery

Redo makes commits durable without flushing data pages; undo enables rollback and MVCC; doublewrite protects against torn pages.

  • Redo log (write-ahead log): every page change is first recorded as a redo record. At commit, the redo is flushed to disk; dirty pages can be written much later. After a crash, InnoDB replays redo to redo committed changes.
  • Since 8.0.30 its size is set by innodb_redo_log_capacity (files live in #innodb_redo). Too small a redo log forces aggressive flushing (checkpoint pressure) under heavy writes.
  • Undo log: before changing a row, InnoDB writes the old version to undo. It is used to roll back and to build older row versions for MVCC. A purge thread deletes undo that no read view needs.
  • Doublewrite buffer: a 16 KB page write can be cut in half by a crash (torn page). InnoDB first writes pages to the doublewrite area, then to the tablespace, so a torn page can be restored. Separate files since 8.0.20.
  • innodb_flush_log_at_trx_commit: 1 = write and fsync at each commit (full ACID, default); 2 = write at commit, fsync about once per second (may lose ~1 s if the OS crashes); 0 = write and fsync about once per second.
  • With binlog on, MySQL uses an internal two-phase commit: redo prepare → binlog write and fsync → redo commit. On recovery, a prepared transaction is committed only if it is in the binlog, so replicas and the source agree.

Interview questions

  • Difference between the redo log and the undo log?
  • How does InnoDB recover after a crash?
  • What is the doublewrite buffer and why is it needed if we have redo?
  • Why does MySQL need two-phase commit between InnoDB and the binlog?

Transactions, MVCC & locking

MVCC & read views

Readers get a consistent snapshot by walking undo chains back to the version their read view can see; readers don't block writers.

  • Each clustered index row has hidden columns: DB_TRX_ID (last transaction that changed it) and DB_ROLL_PTR (pointer to the previous version in undo).
  • A read view is a snapshot of which transactions were active. It stores the lowest active trx id, the next trx id to be assigned, the list of active ids and its own id.
  • Visibility rule: a version is visible if its trx id is below every active id, or is your own; it is invisible if it is at or above the next id, or in the active list. If invisible, follow DB_ROLL_PTR to an older version.
  • REPEATABLE READ creates the read view at the first consistent read in the transaction and reuses it. READ COMMITTED creates a new read view for each statement.
  • Plain SELECT is a consistent (snapshot) read with no locks. SELECT … FOR UPDATE/FOR SHARE, UPDATE and DELETE are locking (current) reads that see the latest committed version.
  • Old versions stay in undo until no read view needs them. A transaction left open for hours keeps all that history alive.

Interview questions

  • How does MVCC work in InnoDB?
  • How do REPEATABLE READ and READ COMMITTED differ in terms of read views?
  • Why can a long-running transaction slow down the whole database?

Transactions & isolation levels

MySQL's default is REPEATABLE READ; it prevents phantoms for snapshot reads via MVCC and for locking reads via next-key locks.

  • autocommit is on by default: each statement is its own transaction unless you START TRANSACTION.
  • Four levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ (MySQL default) and SERIALIZABLE. PostgreSQL and SQL Server default to READ COMMITTED.
  • SERIALIZABLE in InnoDB turns plain SELECTs into FOR SHARE reads (when autocommit is off), so it locks a lot.
  • Many high-traffic setups use READ COMMITTED: fewer gap locks, fewer deadlocks, and each statement sees fresh data. It needs ROW binlog format.
  • DDL statements (CREATE, ALTER, DROP) cause an implicit commit. MySQL DDL is atomic per statement but cannot be rolled back inside a transaction.
  • Set per session: SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; or globally with transaction_isolation.

Interview questions

  • What is MySQL's default isolation level and why does it matter?
  • Does REPEATABLE READ in MySQL prevent phantom reads?
  • Why might you switch to READ COMMITTED?
  • Can you roll back an ALTER TABLE in MySQL?

Row locks, gap/next-key locks & deadlocks

InnoDB locks index records; in REPEATABLE READ locking scans also lock the gaps, and deadlocks are detected and one transaction is rolled back.

  • Record lock: locks one index record. Gap lock: locks the space between records so nothing can be inserted. Next-key lock = record + the gap before it (the RR default for locking scans).
  • An equality search on a unique index that finds a row locks only that record. Range scans and non-unique lookups lock the scanned records and their gaps.
  • Locks are on index entries. If an UPDATE … WHERE has no usable index, InnoDB scans and locks every row it reads, which behaves like a table lock.
  • Insert intention locks let inserts into the same gap at different positions proceed together, but they wait for an existing gap lock. Gap locks don't conflict with each other.
  • 8.0 adds FOR SHARE, plus NOWAIT (fail at once) and SKIP LOCKED (skip locked rows, great for job queues).
  • Deadlocks: InnoDB detects cycles and rolls back the transaction with less work (error 1213). innodb_lock_wait_timeout (default 50 s) covers plain waits (error 1205).

Interview questions

  • What are gap locks and next-key locks?
  • An UPDATE locked far more rows than expected. Why?
  • How do you debug a deadlock in MySQL?
  • How would you build a job queue on MySQL without workers blocking each other?
  • Difference between error 1205 and 1213?

Schema, queries & indexes

Data types & character sets

Choose the smallest correct type, use DECIMAL for money, DATETIME or TIMESTAMP on purpose, and utf8mb4 always.

  • CHAR(n) is fixed length (padded, trailing spaces removed on read); good for fixed codes. VARCHAR(n) stores actual length plus a 1–2 byte length prefix.
  • n counts characters. With utf8mb4 a character can take 4 bytes, so VARCHAR(255) may need up to 1020 bytes. That matters for the 3072-byte index key limit.
  • TIMESTAMP: 4 bytes, stored in UTC and converted using the session time_zone, range 1970 to 2038-01-19. DATETIME: 5 bytes, stored as given (no time zone), range 1000–9999.
  • utf8 in MySQL means utf8mb3 (max 3 bytes, no emoji, deprecated). Use utf8mb4; the 8.0 default collation utf8mb4_0900_ai_ci is accent- and case-insensitive.
  • Money: DECIMAL(p,s) or integer cents, never FLOAT/DOUBLE. BOOL is just TINYINT(1). Integer display widths like INT(11) are deprecated and mean nothing.
  • TEXT/BLOB may be stored off-page and force on-disk temp tables in some queries; index them only with a prefix or full-text index.

Interview questions

  • Difference between CHAR and VARCHAR?
  • DATETIME vs TIMESTAMP — which would you use?
  • What is the difference between utf8 and utf8mb4 in MySQL?

JSON support

MySQL has a native binary JSON type with path operators, JSON_TABLE, and indexing through generated columns, functional or multi-valued indexes.

  • The JSON type validates documents on insert and stores them in a binary format, so reading a key doesn't need to re-parse the whole text.
  • col->'$.path' is JSON_EXTRACT (returns JSON, strings keep quotes). col->>'$.path' also unquotes (JSON_UNQUOTE(JSON_EXTRACT(...))).
  • You can't index a JSON column directly. Index a generated column or a functional index on an expression such as CAST(doc->>'$.type' AS CHAR(20)).
  • Multi-valued indexes (8.0.17+) index every element of an array: CAST(doc->'$.tags' AS CHAR(20) ARRAY), used by MEMBER OF, JSON_CONTAINS and JSON_OVERLAPS.
  • JSON_TABLE turns a JSON array into rows you can join. JSON_ARRAYAGG / JSON_OBJECTAGG build JSON from rows.
  • JSON_SET, JSON_REPLACE and JSON_REMOVE can update in place (partial update), which also keeps ROW binlog events small with binlog_row_value_options=PARTIAL_JSON.

Interview questions

  • How do you index a field inside a JSON column in MySQL?
  • Difference between -> and ->> in MySQL?
  • When would you not use a JSON column?

Reading EXPLAIN

EXPLAIN shows, per table, the access type, chosen index, estimated rows and extra work like filesort or temp tables.

  • Key columns: type (access method), possible_keys, key (index chosen), key_len (how many bytes of a composite index are used), ref, rows (estimate), filtered (% left after conditions), Extra.
  • type from best to worst: system/const (one row by PK/unique) → eq_ref (one row per join row) → ref (non-unique match) → range → index (full index scan) → ALL (full table scan).
  • Extra: Using index = covering; Using where = filter after reading; Using index condition = index condition pushdown; Using filesort = extra sort step; Using temporary = internal temp table; Using join buffer (hash join) = no index for the join.
  • EXPLAIN ANALYZE (8.0.18+) actually runs the query and shows real rows, loops and time per step in tree form. Use it to spot wrong estimates.
  • Estimates come from index statistics. Refresh with ANALYZE TABLE; for non-indexed skewed columns, add histograms (ANALYZE TABLE t UPDATE HISTOGRAM ON col).

Interview questions

  • Which EXPLAIN columns do you look at first?
  • What do 'Using filesort' and 'Using temporary' mean?
  • Difference between EXPLAIN and EXPLAIN ANALYZE?
  • The optimizer picks the wrong index. What do you do?

Index design & query tips

Build composite indexes for real queries: equality columns first, then range or sort; avoid functions on indexed columns; paginate by key.

  • Leftmost prefix: an index on (a, b, c) helps a, a,b and a,b,c, but not b or c alone (8.0's skip scan helps only in limited cases).
  • Order columns equality first, then range/sort. After a range condition (>, BETWEEN, LIKE 'x%'), later columns can't be used to seek.
  • Wrapping a column in a function (WHERE DATE(created_at) = ..., WHERE LOWER(email) = ...) or an implicit type cast prevents index use. Rewrite as a range or add a functional index.
  • LIKE 'abc%' can use a B+tree index; LIKE '%abc' cannot. Use a FULLTEXT index for word search.
  • Avoid OFFSET on deep pages: MySQL reads and throws away all skipped rows. Use keyset pagination (WHERE id > last_id).
  • Every index slows writes and uses buffer pool memory. Find unused ones with sys.schema_unused_indexes and test removal with invisible indexes.

Interview questions

  • What is the leftmost prefix rule?
  • How do you decide the column order in a composite index?
  • Why is deep OFFSET pagination slow and what is the fix?
  • Why might MySQL ignore an index on a column you filter by?

Replication, HA & backups

Replication: binlog formats, async vs semi-sync, GTID

The source writes changes to the binlog; replicas pull it into a relay log and replay it. GTIDs give every transaction a global ID.

  • Binlog formats: STATEMENT logs SQL text (small but unsafe for non-deterministic statements like UUID(), NOW() in some cases or LIMIT without ORDER BY); ROW logs changed rows (default, safest); MIXED uses statement and switches to row when unsafe.
  • Replica threads: a receiver (I/O) thread copies binlog events into the relay log; one or more applier (SQL) threads replay them. 8.0.27+ uses multi-threaded appliers by default (replica_parallel_workers = 4).
  • Asynchronous (default): the source commits without waiting for replicas, so a failover can lose the last transactions.
  • Semi-synchronous: the source waits until at least one replica confirms it has the events in its relay log before returning COMMIT. With AFTER_SYNC (default) this is lossless; after a timeout it falls back to async.
  • GTID = source_uuid:transaction_number. Replicas track which GTIDs they've executed, so SOURCE_AUTO_POSITION = 1 lets them reconnect to any new source without file/position math.
  • The binlog is also what CDC tools like Debezium read to stream changes to Kafka.

Interview questions

  • How does MySQL replication work?
  • Statement vs row vs mixed binlog format?
  • Async vs semi-sync replication?
  • What is a GTID and why use it?

Read replicas, lag & Group Replication / InnoDB Cluster

Replicas scale reads but lag; Group Replication adds consensus-based automatic failover, packaged as InnoDB Cluster.

  • Read replicas take read traffic and backups. Route with the app, ProxySQL or MySQL Router.
  • Replication lag comes from big transactions, single-threaded apply, slow replica hardware, long DDL, or PK-less tables. Seconds_Behind_Source is rough; a heartbeat table (pt-heartbeat) is more accurate.
  • Read-your-writes: send a user's reads to the primary for a short time after they write, or wait on the replica with WAIT_FOR_EXECUTED_GTID_SET(gtid, timeout).
  • Group Replication: a group of servers that agree on each transaction through a Paxos-based protocol; conflicts are detected by certification. Needs a majority, up to 9 members; single-primary mode is the default.
  • InnoDB Cluster = Group Replication + MySQL Shell (AdminAPI to create and manage it) + MySQL Router (routes clients to the current primary). ClusterSet adds a DR cluster in another region; ReplicaSet is the async-only version.
  • Other options: Orchestrator for async topologies, Galera / Percona XtraDB Cluster, and managed services (RDS/Aurora, Cloud SQL, Azure).

Interview questions

  • Users see stale data right after updating their profile. Why, and how do you fix it?
  • What causes replication lag and how do you reduce it?
  • What is InnoDB Cluster?
  • Group Replication vs semi-sync replication?

Backups & point-in-time recovery

Logical dumps for small data, physical hot backups for large data, and binlogs to roll forward to any moment.

  • mysqldump writes SQL. With --single-transaction it takes a consistent InnoDB snapshot without locking writes. Restores are single-threaded and slow on big data.
  • MySQL Shell dump utilities (util.dumpInstance, util.loadDump) are parallel, compressed logical dumps and much faster than mysqldump. mysqlpump is gone in 8.4.
  • Percona XtraBackup (open source) and MySQL Enterprise Backup copy InnoDB files while the server runs, plus the redo generated meanwhile. A prepare step applies redo to make files consistent. Both support incremental backups.
  • Point-in-time recovery (PITR): restore the last full backup, then replay binlogs with mysqlbinlog from the backup's position up to just before the bad event.
  • Keep binlogs long enough (binlog_expire_logs_seconds, default 30 days) and copy them off the server. Other tools: the clone plugin for fast replica provisioning, and disk snapshots.
  • A backup you haven't restored in a test is not a backup. Automate restore drills and measure recovery time.

Interview questions

  • Logical vs physical backup?
  • Someone ran DROP TABLE at 10:15. How do you recover?
  • Why use --single-transaction with mysqldump?

Scaling & operations

Partitioning & sharding (Vitess)

Partitioning splits one table inside one server; sharding splits data across servers, usually with a routing layer like Vitess.

  • Partitioning types: RANGE, LIST, HASH, KEY (plus RANGE COLUMNS / LIST COLUMNS). Each partition is its own B+tree.
  • Main wins: partition pruning (queries with the partition key read fewer partitions) and dropping old data instantly with ALTER TABLE … DROP PARTITION instead of a huge DELETE.
  • Rules: every unique key (including the PK) must include the partition column; partitioned InnoDB tables can't have foreign keys. Queries without the partition key scan all partitions.
  • Sharding spreads rows across many MySQL servers by a shard key (tenant id, user id). It scales writes and storage, but cross-shard joins and transactions become hard.
  • Vitess (CNCF graduated; used by YouTube, Slack, PlanetScale): VTGate is a MySQL-protocol proxy that routes queries, VTTablet runs next to each mysqld, the VSchema and vindexes map keys to shards, and VReplication handles online resharding.
  • Before sharding: tune queries, add replicas and caching, archive old data, scale up. Shard when write volume or data size truly outgrows one primary.

Interview questions

  • Difference between partitioning and sharding?
  • What are the limitations of MySQL partitioning?
  • What is Vitess and how does it shard MySQL?
  • How would you choose a shard key for a multi-tenant SaaS?

Performance tuning & slow query log

Find the worst queries first (slow log, performance_schema), fix them with indexes and rewrites, then tune memory, redo and connections.

  • Slow query log: slow_query_log = ON, long_query_time (default 10 s, often set to 0.5–1 s), optionally log_queries_not_using_indexes. Summarise with pt-query-digest or mysqldumpslow.
  • performance_schema + sys schema: sys.statement_analysis, sys.statements_with_full_table_scans, sys.schema_unused_indexes show the heaviest statements without a log file.
  • Key settings: innodb_buffer_pool_size (biggest lever), innodb_redo_log_capacity, innodb_flush_log_at_trx_commit/sync_binlog, innodb_io_capacity for your disks, max_connections.
  • Per-connection buffers (sort_buffer_size, join_buffer_size) are allocated per session; raising them globally can exhaust RAM.
  • Schema changes on big tables: prefer ALGORITHM=INSTANT (add/drop column in 8.0.29+), then INPLACE, LOCK=NONE; otherwise use gh-ost or pt-online-schema-change.
  • Typical query fixes: add the right composite index, avoid SELECT *, remove N+1 queries in the app, batch writes, and use keyset pagination.

Interview questions

  • A MySQL-backed API got slow. How do you investigate?
  • Which server variables would you tune first?
  • How do you add a column or index to a 500 GB table without downtime?

MySQL vs PostgreSQL

Both are mature open-source RDBMSs; MySQL is simpler with a clustered-PK engine and strong replication tooling, PostgreSQL is richer in SQL and extensions.

  • Storage: InnoDB clusters rows by PK and keeps old versions in undo. PostgreSQL stores rows in a heap, writes new tuple versions in place, and needs VACUUM to clean them.
  • Defaults: MySQL uses REPEATABLE READ; PostgreSQL uses READ COMMITTED and has true SERIALIZABLE (SSI).
  • Features: PostgreSQL has transactional DDL, many index types (GIN, GiST, BRIN), JSONB with GIN indexes, rich extensions (PostGIS, pgvector). MySQL has simpler ops, strong replication ecosystem (Group Replication, Vitess) and very fast PK lookups.
  • Replication: MySQL replicates logical binlog events; PostgreSQL streams physical WAL (plus logical replication).
  • Syntax differences: AUTO_INCREMENT vs IDENTITY/sequences, ON DUPLICATE KEY UPDATE vs ON CONFLICT, backtick vs double-quote identifiers.

Interview questions

  • MySQL vs PostgreSQL: how would you choose?
  • How does MVCC differ between MySQL and PostgreSQL?
  • Why might a query be fast in MySQL but slow in PostgreSQL (or the other way)?