MySQL Interview Master
The most comprehensive collection of 100+ technical MySQL questions. Designed for depth, accuracy, and helping you land your dream backend role.
What is MySQL?
BeginnerMySQL is an open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It is one of the most popular databases in the ...
Expert Answer
What are the main features of MySQL?
BeginnerPrimary features of MySQL include: 1. **Relational Database System**: Stores data in tables with rows and columns. 2. **High Performance**: Optimized for fast r...
Expert Answer
What is the difference between MySQL and SQL?
BeginnerSQL (Structured Query Language) is a standard language used to interact with databases. MySQL is an actual software project (an RDBMS) that implements SQL. - *...
Expert Answer
What is the default port for MySQL?
BeginnerThe default port for MySQL is **3306**.
Expert Answer
SQL Snippet
mysql -h localhost -P 3306 -u root -pWhat is a database in MySQL?
BeginnerIn MySQL, a database is a container that holds a collection of related tables, views, stored procedures, and other database objects. You use the `CREATE DATABAS...
Expert Answer
SQL Snippet
CREATE DATABASE interview_db;What are the common data types in MySQL?
BeginnerMySQL supports several categories of data types: 1. **Numeric**: INT, DECIMAL, FLOAT, DOUBLE. 2. **String**: CHAR, VARCHAR, TEXT, BLOB. 3. **Date and Time**: DA...
Expert Answer
What is the difference between CHAR and VARCHAR?
Beginner**CHAR** is fixed-length. If you define CHAR(10) and store 'ABC', it will use 10 bytes and pad the rest with spaces. **VARCHAR** is variable-length. If you defi...
Expert Answer
How do you create a table in MySQL?
BeginnerYou use the `CREATE TABLE` statement followed by the table name and column definitions.
Expert Answer
SQL Snippet
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);What is a Primary Key?
BeginnerA Primary Key is a column (or set of columns) that uniquely identifies each row in a table. - It cannot contain NULL values. - It must be unique. - A table can...
Expert Answer
What is a Foreign Key?
BeginnerA Foreign Key is a column that creates a link between two tables. It refers to the Primary Key of another table, ensuring referential integrity by preventing or...
Expert Answer
What is the difference between DELETE and TRUNCATE?
Beginner- **DELETE**: A DML command. It deletes rows one by one and can be filtered with a WHERE clause. It is slower and records each row deletion in the transaction l...
Expert Answer
What is a Unique Constraint?
BeginnerA Unique Constraint ensures that all values in a column are distinct. Unlike Primary Keys, a table can have multiple Unique Constraints, and they *can* accept o...
Expert Answer
How do you add a new column to an existing table?
BeginnerYou use the `ALTER TABLE` statement with the `ADD` clause.
Expert Answer
SQL Snippet
ALTER TABLE users ADD phone_number VARCHAR(15);What is the auto_increment attribute?
BeginnerThe `AUTO_INCREMENT` attribute allows a unique number to be generated automatically when a new record is inserted into a table. This is often used for the Prima...
Expert Answer
How do you insert data into a MySQL table?
BeginnerYou use the `INSERT INTO` statement.
Expert Answer
SQL Snippet
INSERT INTO users (username, email)
VALUES ('john_doe', 'john@example.com');What is the WHERE clause used for?
BeginnerThe `WHERE` clause is used to filter records that fulfill a specified condition in SELECT, UPDATE, or DELETE statements.
Expert Answer
SQL Snippet
SELECT * FROM users WHERE username = 'john_doe';What is the LIMIT clause?
BeginnerThe `LIMIT` clause is used to specify the number of records to return. This is useful for pagination or limiting the load on the database.
Expert Answer
SQL Snippet
SELECT * FROM users LIMIT 10 OFFSET 20;How do you sort results in MySQL?
BeginnerYou use the `ORDER BY` clause, followed by `ASC` (ascending) or `DESC` (descending).
Expert Answer
SQL Snippet
SELECT * FROM users ORDER BY created_at DESC;What are Aggregate Functions?
BeginnerAggregate functions perform a calculation on a set of values and return a single value. Common ones include: `COUNT()`, `SUM()`, `AVG()`, `MAX()`, and `MIN()`.
Expert Answer
What is the use of the DISTINCT keyword?
BeginnerThe `DISTINCT` keyword is used to return only unique (different) values from a column.
Expert Answer
SQL Snippet
SELECT DISTINCT country FROM users;What is a NULL value?
BeginnerA NULL value represents missing or unknown data. It is *not* the same as zero or an empty string. You test for it using `IS NULL` or `IS NOT NULL`.
Expert Answer
How do you update existing data in a table?
BeginnerYou use the `UPDATE` statement. Always use a WHERE clause unless you want to update all rows!
Expert Answer
SQL Snippet
UPDATE users
SET email = 'new_email@example.com'
WHERE id = 1;How do you delete a database or a table?
BeginnerYou use the `DROP` command. This is permanent and cannot be undone.
Expert Answer
SQL Snippet
DROP TABLE users;
DROP DATABASE interview_db;What is the LIKE operator?
BeginnerThe `LIKE` operator is used in a WHERE clause to search for a specified pattern in a column. - `%` represents zero, one, or multiple characters. - `_` represen...
Expert Answer
SQL Snippet
SELECT * FROM users WHERE username LIKE 'j%';What is the default storage engine for MySQL?
BeginnerSince MySQL 5.5, the default storage engine is **InnoDB**. It supports ACID transactions, row-level locking, and foreign keys.
Expert Answer
How do you explain Inner Join in MySQL?
IntermediateAn Inner Join returns rows only when there is at least one match in both tables. It is used to combine related data that exists in multiple tables based on a co...
Expert Answer
SQL Snippet
SELECT orders.id, users.username
FROM orders
INNER JOIN users ON orders.user_id = users.id;Explain Left Join and Right Join.
Intermediate- **LEFT JOIN**: Returns all rows from the left table and matched rows from the right table. If no match is found, NULL values are returned for columns of the r...
Expert Answer
What is a Cross Join?
IntermediateA Cross Join returns the Cartesian product of the two tables, meaning it joins every row from the first table with every row from the second table. This is gene...
Expert Answer
How do you use the GROUP BY clause?
IntermediateThe `GROUP BY` clause is used to group rows that have the same values into summary rows, like "find the number of users in each country". It's often used with a...
Expert Answer
SQL Snippet
SELECT country, COUNT(id)
FROM users
GROUP BY country;What is the difference between WHERE and HAVING?
Intermediate- **WHERE**: Filters rows *before* they are grouped. - **HAVING**: Filters groups *after* they are formed. It is specifically used with aggregate functions.
Expert Answer
What is an Index in MySQL?
IntermediateAn index is a data structure used to quickly locate and access data in a table without scanning the entire table. It works like an index in a book. While it spe...
Expert Answer
What are the different types of Indexes in MySQL?
Intermediate1. **Primary Index**: Automatically created on the primary key. 2. **Unique Index**: Ensures column values are unique. 3. **Full-Text Index**: Used for text-bas...
Expert Answer
What is a View in MySQL?
IntermediateA View is a virtual table based on the result-set of an SQL statement. It does not store data itself but provides a simplified or restricted way to look at exis...
Expert Answer
SQL Snippet
CREATE VIEW active_users AS
SELECT id, username FROM users WHERE status = 'active';What are Stored Procedures?
IntermediateA Stored Procedure is a prepared SQL code that you can save and reuse. It's useful for complex logic, reduces network traffic, and can improve performance as th...
Expert Answer
What is a Trigger?
IntermediateA Trigger is a set of SQL statements that automatically execute or 'fire' when an event (INSERT, UPDATE, or DELETE) occurs on a specific table.
Expert Answer
SQL Snippet
CREATE TRIGGER after_user_insert
AFTER INSERT ON users
FOR EACH ROW
INSERT INTO logs (message) VALUES ('New user created');What is a Transaction in MySQL?
IntermediateA transaction is a unit of work that contains one or more SQL statements. MySQL transactions follow **ACID** properties: Atomicity, Consistency, Isolation, and ...
Expert Answer
What are COMMIT and ROLLBACK?
Intermediate- **COMMIT**: Saves the changes made during a transaction permanently to the database. - **ROLLBACK**: Undoes all changes made during the current transaction if...
Expert Answer
What is the difference between a Function and a Stored Procedure?
Intermediate- **Functions**: Must return a single value, can be used in SELECT statements, and only allow input parameters. - **Stored Procedures**: Can return multiple val...
Expert Answer
How do you check current running queries in MySQL?
IntermediateYou can use the `SHOW PROCESSLIST` command to see all active connections and their current queries.
Expert Answer
SQL Snippet
SHOW PROCESSLIST;What is a Full-Text Search?
IntermediateFull-text search (FTS) allows you to search for words or phrases in large text columns efficiently using a specialized index. You use `MATCH()` and `AGAINST()` ...
Expert Answer
SQL Snippet
SELECT * FROM posts
WHERE MATCH(title, content) AGAINST('database');What is Query Optimization?
IntermediateQuery optimization is the process of writing SQL in a way that uses minimal resources (CPU, Memory) and executes as fast as possible. This often involves using ...
Expert Answer
How do you use the EXPLAIN keyword?
IntermediateThe `EXPLAIN` keyword is used before a query to see how MySQL intends to execute it. It reveals if indexes are being used and how many rows are being scanned.
Expert Answer
SQL Snippet
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';What is a Subquery?
IntermediateA subquery is a query nested inside another SQL statement. It's often used in WHERE or FROM clauses to filter data based on the results of another query.
Expert Answer
SQL Snippet
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders);What is the difference between UNION and UNION ALL?
Intermediate- **UNION**: Combines the results of two SELECT statements and removes duplicate rows. - **UNION ALL**: Combines results but includes duplicates. It is faster b...
Expert Answer
What is the COALESCE() function?
IntermediateThe `COALESCE()` function returns the first non-null value in a list. It is very useful for providing default values when data might be NULL.
Expert Answer
SQL Snippet
SELECT COALESCE(phone, 'No Phone Provided') FROM users;What is a Composite Index?
IntermediateA composite index is an index on multiple columns. It is useful for queries that filter by more than one column in a specific order.
Expert Answer
How do you find the second highest salary from a table?
IntermediateYou can use subqueries or the `LIMIT` clause with an offset.
Expert Answer
SQL Snippet
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;What is Referential Integrity?
IntermediateReferential integrity is a database concept that ensures the relationship between tables remains consistent. For example, you cannot delete a row from a 'users'...
Expert Answer
What are the ON DELETE CASCADE and ON UPDATE CASCADE options?
IntermediateThese are rules for foreign keys: - **ON DELETE CASCADE**: If a parent row is deleted, automatically delete all child rows. - **ON UPDATE CASCADE**: If a parent...
Expert Answer
What is the difference between NOW() and CURDATE()?
Intermediate- **NOW()**: Returns the current date and time (YYYY-MM-DD HH:MM:SS). - **CURDATE()**: Returns only the current date (YYYY-MM-DD).
Expert Answer
What are the different isolation levels in MySQL?
AdvancedMySQL (InnoDB) supports four isolation levels: 1. **READ UNCOMMITTED**: Lowest isolation, allows dirty reads. 2. **READ COMMITTED**: Prevents dirty reads, but a...
Expert Answer
Explain the ACID properties in MySQL.
Advanced- **Atomicity**: All operations in a transaction succeed or none do (All or nothing). - **Consistency**: A transaction transforms the database from one valid st...
Expert Answer
What is Deadlock in MySQL and how to handle it?
AdvancedA deadlock occurs when two or more transactions mutually hold locks that the others need, causing them to wait forever. InnoDB automatically detects deadlocks a...
Expert Answer
What is the difference between Optimistic and Pessimistic Locking?
Advanced- **Pessimistic Locking**: Assumes a conflict will happen and locks the records before updating (`SELECT ... FOR UPDATE`). - **Optimistic Locking**: Assumes no ...
Expert Answer
What is a Binary Log (Binlog) in MySQL?
AdvancedThe binary log contains 'events' that describe database changes such as table creation operations or changes to table data. It is crucial for **Replication** an...
Expert Answer
How does MySQL Replication work?
AdvancedMySQL replication typically uses a Source-Replica model: 1. The Source writes changes to its **Binary Log**. 2. The Replica connects to the Source and reads the...
Expert Answer
What is the difference between Statement-Based and Row-Based Replication?
Advanced- **Statement-Based**: The actual SQL query is sent to replicas. It is efficient but can cause issues with non-deterministic functions like `NOW()`. - **Row-Bas...
Expert Answer
What is horizontal and vertical scaling in MySQL?
Advanced- **Vertical**: Adding more resources (CPU, RAM, SSD) to a single server. - **Horizontal**: Adding more servers to handle the load, often using Read Replicas or...
Expert Answer
What is Sharding?
AdvancedSharding is the process of splitting a large database into smaller, faster, more easily managed parts called shards. Each shard is a separate database stored on...
Expert Answer
Explain Query Cache in MySQL.
AdvancedQuery cache stores the exact text of a SELECT statement together with the corresponding result. If an identical statement is received later, the server retrieve...
Expert Answer
What is a Buffer Pool in InnoDB?
AdvancedThe buffer pool is a memory area where InnoDB caches table and index data as it is accessed. It is the most important setting for MySQL performance. A large buf...
Expert Answer
What are Hidden Columns in MySQL 8.0?
AdvancedInvisible columns are columns that are not visible to `SELECT *` queries unless explicitly named. They are useful for adding infrastructure columns (like timest...
Expert Answer
What is the difference between MyISAM and InnoDB?
Advanced- **InnoDB**: Supports transactions, row-level locking, foreign keys, and is crash-resilient. - **MyISAM**: Does not support transactions, only uses table-level...
Expert Answer
How to perform a backup of a MySQL database?
AdvancedCommon methods include: 1. **mysqldump**: Logical backup (generates SQL file). 2. **MySQL Shell (util.dumpInstance)**: Faster, multi-threaded logical backup. 3....
Expert Answer
SQL Snippet
mysqldump -u root -p database_name > backup.sqlWhat is slow query log?
AdvancedThe slow query log consists of SQL statements that take more than `long_query_time` seconds to execute. It is the primary tool for identifying performance bottl...
Expert Answer
Explain Window Functions in MySQL 8.0.
AdvancedWindow functions perform calculations across a set of table rows that are related to the current row. Unlike aggregate functions, they do not group rows into a ...
Expert Answer
SQL Snippet
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) as rank FROM employees;What are Common Table Expressions (CTEs)?
AdvancedA CTE is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It makes complex queries more readable.
Expert Answer
SQL Snippet
WITH RegionalSales AS (
SELECT region, SUM(amount) AS total FROM sales GROUP BY region
)
SELECT * FROM RegionalSales WHERE total > 10000;What is JSON support in MySQL?
AdvancedMySQL (since 5.7) provides a JSON data type that allows for efficient storage and querying of JSON documents. It includes functions like `JSON_EXTRACT()` and su...
Expert Answer
SQL Snippet
SELECT info->'$.customer_name' FROM orders;Explain the concept of 'Covering Index'.
AdvancedA covering index is an index that includes all the columns requested in a query. In this case, MySQL can fulfill the request by reading the index only, without ...
Expert Answer
What is the purpose of the Performance Schema?
AdvancedThe Performance Schema is a tool for monitoring MySQL server execution at a very low level. It collects statistics on events, resource usage, and internal wait ...
Expert Answer
What is an 'Upsert' in MySQL?
AdvancedAn Upsert (Update or Insert) is performed in MySQL using the `INSERT ... ON DUPLICATE KEY UPDATE` syntax. If a record with the same unique key exists, it update...
Expert Answer
SQL Snippet
INSERT INTO stats (id, count) VALUES (1, 1)
ON DUPLICATE KEY UPDATE count = count + 1;How to secure a MySQL installation?
Advanced1. Run `mysql_secure_installation`. 2. Use strong passwords. 3. Restrict host access for the 'root' user. 4. Enable SSL for connections. 5. Follow the 'Principl...
Expert Answer
What is the difference between a Temporary Table and a Derived Table?
Advanced- **Temporary Table**: Exists only for the duration of the current session and is visible only to that session. It can be referenced multiple times. - **Derived...
Expert Answer
What is 'Ghost Rows' or 'Phantom Read'?
AdvancedA phantom read occurs when a transaction reads a set of rows that satisfy a condition, but another transaction inserts a new row that also satisfies the conditi...
Expert Answer
What is adaptive hash index?
AdvancedAdaptive Hash Index (AHI) is an InnoDB feature that automatically creates hash indexes for frequently accessed pages in the Buffer Pool. This allows B-Tree page...
Expert Answer
How to find duplicate records in a table?
ScenarioYou can use `GROUP BY` and `HAVING` to find values that appear more than once.
Expert Answer
SQL Snippet
SELECT email, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1;How to delete duplicate records keeping only one?
ScenarioOne way is to use a `JOIN` on the same table and delete rows with a higher ID.
Expert Answer
SQL Snippet
DELETE u1 FROM users u1
INNER JOIN users u2
WHERE u1.id > u2.id AND u1.email = u2.email;Write a query to get the nth highest salary.
ScenarioYou can use the `LIMIT` clause with an offset (n-1).
Expert Answer
SQL Snippet
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 4; -- 5th highestHow to select rows with a date in the last 30 days?
ScenarioUse `DATE_SUB()` or `INTERVAL` arithmetic.
Expert Answer
SQL Snippet
SELECT * FROM orders
WHERE order_date >= DATE_SUB(NOW(), INTERVAL 30 DAY);How to find rows where a column contains only numbers?
ScenarioYou can use a Regular Expression.
Expert Answer
SQL Snippet
SELECT * FROM table
WHERE column_name REGEXP '^[0-9]+$';Scenario: Your production database is slow. What are your first steps?
Scenario1. Check `SHOW PROCESSLIST` for stuck/long-running queries. 2. Examine the **Slow Query Log**. 3. Check server metrics (CPU, IOPS, Memory/Buffer Pool usage). 4....
Expert Answer
How to swap values of two columns in a single UPDATE statement?
ScenarioIn MySQL, you can simply set them equal to each other in one line.
Expert Answer
SQL Snippet
UPDATE table SET col1 = col2, col2 = col1;How to copy data from one table to another?
ScenarioUse `INSERT INTO ... SELECT`.
Expert Answer
SQL Snippet
INSERT INTO archive_users (id, name)
SELECT id, name FROM users WHERE active = 0;How to find the length of the longest string in a column?
ScenarioUse the `MAX()` and `LENGTH()` functions.
Expert Answer
SQL Snippet
SELECT MAX(LENGTH(description)) FROM products;Scenario: You need to store hierarchical data (like categories/subcategories). How do you design it?
ScenarioCommon patterns include: 1. **Adjacency List**: Each row has a `parent_id` (Simple, but hard to query deep trees). 2. **Nested Sets**: Uses `lft` and `rgt` valu...
Expert Answer
How to get the first 3 characters of a string?
ScenarioUse the `LEFT()` or `SUBSTRING()` function.
Expert Answer
SQL Snippet
SELECT LEFT(username, 3) FROM users;How to combine first_name and last_name into one column?
ScenarioUse the `CONCAT()` function.
Expert Answer
SQL Snippet
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;How to find the number of days between two dates?
ScenarioUse the `DATEDIFF()` function.
Expert Answer
SQL Snippet
SELECT DATEDIFF('2026-12-31', '2026-01-01');Scenario: A user reports they can't login, but the database seems fine. What DB-related things do you check?
Scenario1. Check if the user account is locked or expired in `mysql.user`. 2. Verify there are no 'max_connections' or 'max_user_connections' limits being hit. 3. Check...
Expert Answer
How to get the last inserted ID?
ScenarioUse the `LAST_INSERT_ID()` function immediately after the insert.
Expert Answer
SQL Snippet
SELECT LAST_INSERT_ID();How to return a random row from a table?
ScenarioUse `ORDER BY RAND() LIMIT 1`. **Warning**: This is slow on large tables as it requires a full table scan.
Expert Answer
SQL Snippet
SELECT * FROM users ORDER BY RAND() LIMIT 1;How to convert a string to uppercase?
ScenarioUse `UPPER()` or `UCASE()`.
Expert Answer
SQL Snippet
SELECT UPPER(username) FROM users;How to check the version of MySQL you are using?
ScenarioUse the `VERSION()` function or `SELECT @@version;`.
Expert Answer
SQL Snippet
SELECT VERSION();Scenario: You want to ensure no two orders are placed for the same product at the exact same millisecond. How?
Scenario1. Use a **Unique Constraint** on a composite of product_id and timestamp (if timestamp has enough precision). 2. Use a **Transaction** with `SERIALIZABLE` isol...
Expert Answer
How to find all tables in a database?
ScenarioUse `SHOW TABLES;` or query `information_schema.tables`.
Expert Answer
SQL Snippet
SHOW TABLES;How to rename a table?
ScenarioUse the `RENAME TABLE` statement.
Expert Answer
SQL Snippet
RENAME TABLE old_name TO new_name;How to grant all privileges to a user on a specific database?
ScenarioUse the `GRANT` statement.
Expert Answer
SQL Snippet
GRANT ALL PRIVILEGES ON db_name.* TO 'user'@'localhost';How to see the structure of a table?
ScenarioUse `DESCRIBE` or `SHOW CREATE TABLE`.
Expert Answer
SQL Snippet
DESCRIBE users;Scenario: You deleted a row by mistake. How do you get it back?
Scenario1. If you are in a transaction and haven't committed, use `ROLLBACK`. 2. If not, you must restore from a **Backup**. 3. If **Binary Logging** is enabled, you ca...
Expert Answer
How to empty a table without deleting it?
ScenarioUse `TRUNCATE TABLE`.
Expert Answer
SQL Snippet
TRUNCATE TABLE logs;