Technology

MySQL Interview Questions and Answers

MySQL is the most popular open-source database for web applications. These MySQL interview questions cover data types, keys and basic queries for freshers, then storage engines, indexing, transactions and isolation levels, replication, backups and performance tuning for experienced developers and DBAs.

30 questions · Updated

Reading answers is not the same as saying them.Practise MySQL questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
MySQL Interview Questions with answers. Examples: What is MySQL, and where is it used? What is the difference between CHAR and VARCHAR? What does AUTO_INCREMENT do? What is the difference between InnoDB and MyISAM?
MySQL Interview Questions: 30 questions with model answers on this page.

Basic MySQL interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is MySQL, and where is it used?

Answer flow · 4 steps
  1. MySQL is an open-source relational database management system owned by Oracle.

  2. It stores data in tables and is queried with SQL.

  3. It is used by WordPress, Laravel and countless web applications, and by large companies such as Facebook and Uber at scale.

  4. MariaDB is a popular fork.

2. What is the difference between CHAR and VARCHAR?

Answer flow · 3 steps
  1. CHAR has a fixed length and pads shorter values with spaces, which suits values of constant length such as country codes.

  2. VARCHAR has variable length and stores only the characters used plus one or two bytes for the length, so it saves space for values like names and emails.

  3. TEXT is for long content.

3. What does AUTO_INCREMENT do?

Answer flow · 3 steps
  1. AUTO_INCREMENT automatically generates a unique, increasing number for a column, usually the primary key, when a new row is inserted.

  2. LAST_INSERT_ID() returns the value generated in the current session.

  3. Gaps can appear after rollbacks or deletes, so values should not be relied on to be continuous.

4. Which data types does MySQL support?

Numeric types (TINYINT, INT, BIGINT, DECIMAL, FLOAT, DOUBLE), strings (CHAR, VARCHAR, TEXT, BLOB, ENUM, SET), dates and times (DATE, TIME, DATETIME, TIMESTAMP, YEAR), JSON, and spatial types. Choosing the smallest suitable type saves storage and memory and makes indexes faster, for example TINYINT for a status flag rather than INT.

5. Why use DECIMAL instead of FLOAT for money?

Answer flow · 3 steps
  1. FLOAT and DOUBLE store approximate binary values, so 0.1 + 0.2 may not equal exactly 0.3, and rounding errors add up in financial calculations.

  2. DECIMAL(10,2) stores exact decimal values with fixed precision, so amounts such as prices, balances and taxes are always correct.

  3. FLOAT suits scientific measurements where tiny errors do not matter.

6. What is the difference between DATETIME and TIMESTAMP?

Answer flow · 3 steps
  1. DATETIME stores a date and time exactly as given, with a range from year 1000 to 9999, and no time zone conversion.

  2. TIMESTAMP stores values in UTC and converts them to and from the session time zone, with a range from 1970 to 2038.

  3. TIMESTAMP suits event times across time zones; DATETIME suits dates such as birthdays or appointments that should not shift.

7. Why should you use utf8mb4?

In MySQL, the old utf8 (utf8mb3) charset stores at most three bytes per character, so it cannot store emojis and some rare characters. utf8mb4 is real UTF-8 with four bytes, supporting every character, and is the default in MySQL 8 with the utf8mb4_0900_ai_ci collation. Using it everywhere avoids broken text and errors when users enter emojis.

8. How do you create users and grant privileges?

Answer flow · 3 steps
  1. CREATE USER 'app'@'%' IDENTIFIED BY 'strong-password'; then GRANT SELECT, INSERT, UPDATE, DELETE ON shop.* TO 'app'@'%';.

  2. Applications should get only the privileges they need on their own database, never root.

  3. MySQL 8 supports roles to group privileges, SHOW GRANTS shows a user's rights, and REVOKE removes them.

9. How do you see a table's structure and indexes?

DESCRIBE table or SHOW COLUMNS FROM table lists columns and types, SHOW CREATE TABLE table shows the full definition including indexes, keys, engine and charset, and SHOW INDEX FROM table lists indexes with their cardinality. information_schema tables give the same data for queries across many tables.

10. Does MySQL support FULL OUTER JOIN?

No. MySQL supports INNER, LEFT, RIGHT and CROSS joins, but not FULL OUTER JOIN. You can emulate it by combining a LEFT JOIN and a RIGHT JOIN with UNION, which removes duplicate matched rows, or by using a LEFT JOIN plus a RIGHT JOIN filtered to unmatched rows with UNION ALL for better performance.

11. What does GROUP_CONCAT do?

Answer flow · 3 steps
  1. GROUP_CONCAT joins values from a group into one string, such as listing all product names per order: SELECT order_id, GROUP_CONCAT(product_name ORDER BY product_name SEPARATOR ', ') FROM order_items GROUP BY order_id.

  2. The result is cut off at group_concat_max_len (1024 bytes by default), which may need increasing.

  3. JSON_ARRAYAGG is an alternative that returns a JSON array.

Intermediate MySQL interview questions

Applied problems, trade-offs and questions about your own projects.

12. What is the difference between InnoDB and MyISAM?

Answer flow · 3 steps
  1. InnoDB is the default engine: it supports transactions, row-level locking, foreign keys and crash recovery, which suits almost all applications.

  2. MyISAM uses table-level locking, has no transactions or foreign keys and can lose data on a crash.

  3. MyISAM is now considered legacy.

13. What are the transaction isolation levels in MySQL?

READ UNCOMMITTED allows dirty reads, READ COMMITTED sees only committed data, REPEATABLE READ (the InnoDB default) gives a consistent snapshot for the whole transaction, and SERIALIZABLE makes transactions behave as if run one after another. Higher levels prevent more anomalies (dirty reads, non-repeatable reads and phantoms) but increase locking and contention.

14. What is a clustered index in InnoDB?

Answer flow · 3 steps
  1. In InnoDB, table data is stored in the order of the primary key, which is the clustered index.

  2. Secondary indexes store the primary key value, so a lookup by a secondary index finds the primary key and then reads the row.

  3. That is why a short primary key is better, and why a covering index that contains all needed columns avoids the second lookup.

15. How do you find slow queries in MySQL?

I enable the slow query log with a long_query_time threshold, analyse it with pt-query-digest or mysqldumpslow, and check performance_schema and sys schema views for the most expensive statements. For a specific query I run EXPLAIN or EXPLAIN ANALYZE to see whether it uses indexes, how many rows it scans and whether it uses temporary tables or filesort.

16. How do you read the output of EXPLAIN in MySQL?

Key columns are type (from best to worst: const, eq_ref, ref, range, index, ALL, where ALL means a full table scan), possible_keys and key (which index was chosen), rows (estimated rows examined), filtered, and Extra, where "Using index" means a covering index, and "Using filesort" or "Using temporary" signal extra work. EXPLAIN ANALYZE runs the query and shows actual times.

17. What is the leftmost prefix rule for composite indexes?

Answer flow · 3 steps
  1. A composite index on (a, b, c) can be used for queries filtering on a, on a and b, or on a, b and c, but not on b or c alone, because the index is sorted by a first.

  2. A range condition on a column stops later columns from being used for further filtering.

  3. So the column order should match common queries, typically equality columns first and range columns last.

18. What is a covering index?

Answer flow · 3 steps
  1. A covering index contains every column a query needs, so MySQL can answer it from the index alone without reading the table rows, which EXPLAIN shows as "Using index".

  2. For example, an index on (customer_id, created_at, total) covers SELECT created_at, total FROM orders WHERE customer_id = 42.

  3. It greatly speeds up frequent queries, at the cost of larger indexes.

19. How do JSON columns and generated columns work?

Answer flow · 3 steps
  1. The JSON type stores validated JSON documents, queried with JSON_EXTRACT or the -> and ->> operators.

  2. JSON values cannot be indexed directly, so you create a generated column that extracts a value, such as a city from an address, and index it, or use a functional index in MySQL 8.

  3. Generated columns can also compute values such as a full name or a total.

20. How do you do an upsert in MySQL?

INSERT ... ON DUPLICATE KEY UPDATE inserts a row, or updates it if a primary key or unique key already exists, such as INSERT INTO stock (sku, qty) VALUES ('A1', 5) ON DUPLICATE KEY UPDATE qty = qty + 5. INSERT IGNORE skips duplicates silently, and REPLACE deletes and reinserts the row, which can trigger cascading deletes, so it is used carefully.

21. What kinds of locks does InnoDB use?

Answer flow · 3 steps
  1. InnoDB uses row-level locks: shared locks for reads with FOR SHARE and exclusive locks for writes and SELECT ... FOR UPDATE.

  2. In Repeatable Read, it also uses gap locks and next-key locks on index ranges to prevent phantom rows, which can surprise developers by blocking inserts.

  3. Statements that cannot use an index may lock many rows, so good indexes reduce lock contention.

22. When would you use views and stored procedures in MySQL?

Answer flow · 3 steps
  1. Views simplify complex queries for reporting and restrict which columns users can see.

  2. Stored procedures and functions keep logic in the database, which can reduce round trips for batch operations, and events schedule recurring jobs.

  3. Most teams keep business logic in the application for easier testing and deployment, and use procedures only where they clearly help.

High level MySQL interview questions

System design, deep internals, leadership and tough follow-ups.

23. How does MySQL replication work?

Answer flow · 4 steps
  1. The source server writes changes to its binary log.

  2. Replicas read the binary log through an I/O thread into a relay log and apply the changes with SQL threads.

  3. Replication can be asynchronous (default) or semi-synchronous, and GTIDs make failover easier.

  4. Replicas are used for read scaling, backups and high availability; Group Replication and InnoDB Cluster provide automatic failover.

24. What is a deadlock, and how do you handle it?

Answer flow · 4 steps
  1. A deadlock happens when two transactions each hold a lock the other needs.

  2. InnoDB detects it and rolls back one transaction with an error.

  3. I prevent deadlocks by accessing tables and rows in a consistent order, keeping transactions short, using proper indexes so fewer rows are locked, and retrying the failed transaction in the application.

  4. SHOW ENGINE INNODB STATUS shows the latest deadlock.

25. How do you back up and restore a MySQL database?

Answer flow · 4 steps
  1. Logical backups with mysqldump or mysqlpump export SQL statements, which is simple and portable but slow for large databases; --single-transaction gives a consistent InnoDB snapshot without locking.

  2. Physical backups with Percona XtraBackup or MySQL Enterprise Backup copy data files and are much faster.

  3. Combined with binary logs, they allow point-in-time recovery.

  4. Backups must be tested by restoring them regularly.

26. What are the major features of MySQL 8?

Window functions and common table expressions (including recursive), roles, a transactional data dictionary, invisible indexes for safely testing index removal, descending indexes, functional indexes, JSON improvements, utf8mb4 as default, instant ADD COLUMN, better optimiser histograms, and the stronger caching_sha2_password authentication. MySQL now also has LTS and innovation release tracks.

27. Which MySQL settings matter most for performance?

innodb_buffer_pool_size (often 60 to 75% of RAM on a dedicated server) so data and indexes stay in memory, innodb_log_file_size or innodb_redo_log_capacity for write-heavy loads, innodb_flush_log_at_trx_commit for the durability versus speed trade-off, max_connections combined with connection pooling, and tmp_table_size. Query and index design usually matter more than settings.

28. How does partitioning work in MySQL?

Answer flow · 3 steps
  1. Partitioning splits one table into parts stored separately, by RANGE (such as by year), LIST, HASH or KEY.

  2. Queries that filter on the partition key only read relevant partitions, and dropping an old partition deletes old data instantly.

  3. Every unique key must include the partition column, foreign keys are not supported, and it does not help queries that cannot be pruned.

29. How do you make MySQL highly available?

Answer flow · 3 steps
  1. Use replication with automatic failover.

  2. InnoDB Cluster combines Group Replication (synchronous, multi-node replication with automatic primary election), MySQL Router and MySQL Shell.

  3. Alternatives are asynchronous or semi-synchronous replicas with Orchestrator, ProxySQL for routing and read/write splitting, or managed services such as Amazon RDS Multi-AZ and Aurora.

30. How do you change the schema of a large table without downtime?

Answer flow · 3 steps
  1. MySQL 8 can add columns instantly (ALGORITHM=INSTANT) and perform many changes in place with LOCK=NONE.

  2. For changes that would copy and lock a huge table, use tools such as gh-ost or pt-online-schema-change, which copy data to a new table in the background, keep it in sync and swap it in.

  3. Changes should be backward compatible so old and new application versions both work.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a database engineer interview?

See all Database Engineer interview questions, covering SQL, MySQL, PostgreSQL, Oracle, SQL Server and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields