For a MySQL interview for 10+ years of experience, we can expect questions on performance optimization, indexing, query tuning, replication, sharding, transactions, security, and architecture. Here are some key regularly asked questions with answers:
1. MySQL Performance Optimization
Question 1. How do you optimize a slow query in MySQL?
First, let's Check the execution Plan. We can use EXPLAIN to analyze query execution.
EXPLAIN SELECT * FROM orders WHERE status = 'pending';
Indexes: Ensure proper indexes on frequently searched columns.
Fetching Columns: Fetch only necessary columns, do not use select *.
Optimize Joins: Use indexed columns for joins for fast fetching.
Use Query Caching: Enable MySQL query cache.
Partition Large Tables: Use partitioning for high-volume data.
Denormalization: Reduce joins by adding redundant data when necessary.
Optimize WHERE Conditions: Avoid LIKE '%term%' as it prevents index usage.
2. Indexing & Query Execution
Question 2. What are the different types of indexes in MySQL?
Primary Key Index: Unique and clustered index for the primary key.
Unique Index: Ensures unique values in a column.
Full-text Index: Used for text searching (MATCH() AGAINST()).
Composite Index: Index on multiple columns.
Spatial Index: For spatial (GIS) data.
B-Tree Index: Default index type for most engines.
Hash Index: Used in MEMORY tables for fast lookups.
3. Transactions & Concurrency
Question 3. What are ACID properties in MySQL?
Atomicity: Transactions are all or nothing.
Consistency: Ensures data integrity before and after transactions.
Isolation: Transactions operate independently (depends on isolation level).
Durability: Committed transactions persist even after system failure.
You can explain it in detail as below.
ACID is a set of properties that guarantee database transactions are processed reliably. MySQL supports ACID compliance through its various storage engines, most notably InnoDB (which is the default storage engine since MySQL 5.5).
Atomicity
Ensures that all operations in a transaction are completed successfully; if any operation fails, the entire transaction is rolled back
In MySQL, statements like COMMIT and ROLLBACK help manage transaction atomicity
Consistency
Ensures that a transaction can only bring the database from one valid state to another
Maintains database integrity constraints, cascades, triggers, and any defined rules
Isolation
Ensures that concurrent execution of transactions leaves the database in the same state as if the transactions were executed sequentially
MySQL offers different isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ (default), and SERIALIZABLE
Durability
Ensures that once a transaction is committed, it remains committed even in case of system failure.
MySQL achieves this through write-ahead logging and data flushing techniques.
MySQL have different storage engines and they have different ACID compliance characteristics:
InnoDB is Fully ACID-compliant. MyISAM is not ACID-compliant (lacks transaction support).MEMORY and ARCHIVE Not ACID-compliant
To use ACID transactions in MySQL, you should follow the syntax:
START TRANSACTION;
-- SQL operations here
COMMIT; -- or ROLLBACK if something fails
Question 4. What are the different transaction isolation levels in MySQL?
READ UNCOMMITTED: No isolation, dirty reads possible.
READ COMMITTED: No dirty reads, but non-repeatable reads can occur.
REPEATABLE READ (Default in MySQL): No dirty or non-repeatable reads.
SERIALIZABLE: Highest isolation, full locking, worst performance.
4. MySQL Replication & High Availability
Question 5. What are different MySQL replication types?
Asynchronous Replication: Default MySQL replication (Master-Slave).
Semi-Synchronous Replication: Slower but guarantees at least one slave has the latest data.
Group Replication: Multi-master replication for high availability.
GTID (Global Transaction ID) Replication: Ensures reliable replication.
Q6. How do you set up Master-Slave replication in MySQL?
A:
Enable Binary Logging on Master:
ini
[mysqld]
log-bin=mysql-bin
server-id=1
Create a Replication User:
CREATE USER 'replica'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replica'@'%';
Get Master's Current Log Position:
SHOW MASTER STATUS;
Configure Slave Server:
[mysqld]
server-id=2
Start Replication on Slave:
CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='replica', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154;
START SLAVE;
SHOW SLAVE STATUS\G;
5. MySQL Partitioning & Sharding
Q7. What are different types of partitioning in MySQL?
A:
RANGE Partitioning: Based on value ranges.
PARTITION BY RANGE (year(order_date)) (
PARTITION p0 VALUES LESS THAN (2020),
PARTITION p1 VALUES LESS THAN (2023)
);
LIST Partitioning: Based on a predefined list.
HASH Partitioning: Distributes rows across partitions using a hash function.
KEY Partitioning: Like hash but uses MySQL’s internal hashing.
Q8. What is database sharding, and how is it different from partitioning?
A:
Partitioning: Splitting a single table into multiple physical partitions but managed within one MySQL instance.
Sharding: Distributing data across multiple MySQL instances (databases). Each shard is an independent database, and queries are directed based on data distribution.
6. MySQL Security
Q9. How do you secure a MySQL database?
A:
Disable remote root login:
UPDATE mysql.user SET host='localhost' WHERE user='root';
Use Strong Passwords & Authentication: Enforce mysql_native_password or caching_sha2_password.
Grant Least Privilege: Use GRANT instead of giving full privileges.
GRANT SELECT, INSERT ON mydb.* TO 'user'@'host';
Enable Firewall & IP Whitelisting.
Encrypt Connections (SSL/TLS).
Enable Audit Logging: Use MySQL Enterprise Audit.
7. MySQL Storage Engines
Q10. What are the differences between InnoDB and MyISAM?
Feature
InnoDB
MyISAM
Transactions
✅ Yes (ACID-compliant)
❌ No Transactions
Foreign Keys
✅ Supports Foreign Keys
❌ No Foreign Keys
Locking
✅ Row-level Locking
❌ Table-level Locking
Performance
🚀 Better for Read-Write
🔥 Faster for Read-Heavy Workloads
Crash Recovery
✅ Yes (Uses Redo Logs)
❌ No (Might Corrupt Data)
8. Advanced MySQL Topics
Q11. What is a Common Table Expression (CTE) in MySQL?
A:
CTEs simplify complex queries using WITH:
WITH recent_orders AS (
SELECT * FROM orders WHERE order_date > '2024-01-01'
)
SELECT * FROM recent_orders WHERE status = 'pending';
Q12. How does MySQL handle Deadlocks?
A:
A deadlock occurs when two transactions hold locks on resources the other needs.
MySQL automatically detects deadlocks and rolls back one transaction.
Use SHOW ENGINE INNODB STATUS; to debug deadlocks.
9. Backup & Recovery
Q13. How do you take a MySQL backup and restore it?
A:
Backup:
sh
mysqldump -u root -p mydatabase > backup.sql
Restore:
sh
mysql -u root -p mydatabase < backup.sql
10. MySQL JSON & NoSQL Features
Q14. How does MySQL handle JSON data?
A:
MySQL supports JSON with functions like:
sql
SELECT JSON_EXTRACT('{"name": "John", "age": 30}', '$.name');
Can I index non unique columns
Yes, you can index non-unique columns in MySQL. In fact, most indexes are created on non-unique columns to improve query performance.
Types of Indexes on Non-Unique Columns
Single-Column Index (Non-Unique)
Helps speed up searches even if values are repeated.
Example:
CREATE INDEX idx_status ON orders(status);
Improves performance of:
SELECT * FROM orders WHERE status = 'pending';
Composite Index (Multiple Columns, Non-Unique)
Indexing multiple columns together.
Example:
CREATE INDEX idx_status_date ON orders(status, order_date);
Optimized for queries like:
SELECT * FROM orders WHERE status = 'pending' AND order_date > '2024-01-01';
Full-Text Index (For Searching Large Text Fields)
Used in TEXT or VARCHAR columns for searching.
Example:
CREATE FULLTEXT INDEX idx_description ON products(description);
Improves performance of:
SELECT * FROM products WHERE MATCH(description) AGAINST ('laptop');
Covering Index (Helps Avoid Extra Reads from Table)
If a query selects only indexed columns, MySQL fetches data directly from the index instead of reading the table.
Example:
CREATE INDEX idx_name_age ON users(name, age);
Optimized for:
SELECT name, age FROM users WHERE name = 'John';
Things to Remember
✅ Indexes on non-unique columns improve query performance but do not enforce uniqueness.
✅ Too many indexes slow down writes (INSERT, UPDATE, DELETE) since indexes need to be updated.
✅ Use EXPLAIN to check if the index is being used in queries.
✅ For high-duplicate values (low cardinality), indexes may not be effective. Consider partitioning instead.
Final Thoughts
For a 10+ years experienced role, focus on:
Performance tuning & indexing
Replication & high availability
Transactions & isolation levels
Sharding & partitioning
Security & best practices
Would you like a custom mock interview for practice? 🚀
Comments
Post a Comment