MySQL Interview Master

The most comprehensive collection of 100+ technical MySQL questions. Designed for depth, accuracy, and helping you land your dream backend role.

0 / 100 MasteredPerformance & ACIDQuery Optimization
Showing 100 high-quality results in All Questions category.
1
What is MySQL?
Beginner

MySQL 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
MySQL 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 world, known for its reliability, ease of use, and performance. It follows a client-server architecture and is a core component of the LAMP (Linux, Apache, MySQL, PHP/Python/Perl) stack.
Beginner
2
What are the main features of MySQL?
Beginner

Primary 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
Primary features of MySQL include: 1. **Relational Database System**: Stores data in tables with rows and columns. 2. **High Performance**: Optimized for fast read and write operations. 3. **Scalability**: Can handle large datasets and high traffic with ease. 4. **ACID Compliance**: Supports transactions via InnoDB engine. 5. **Security**: Multi-layered security with host-based verification and encrypted connections.
Beginner
3
What is the difference between MySQL and SQL?
Beginner

SQL (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
SQL (Structured Query Language) is a standard language used to interact with databases. MySQL is an actual software project (an RDBMS) that implements SQL. - **SQL**: A language. - **MySQL**: A database engine that understands that language.
Beginner
4
What is the default port for MySQL?
Beginner

The default port for MySQL is **3306**.

Expert Answer
The default port for MySQL is **3306**.
SQL Snippet
mysql -h localhost -P 3306 -u root -p
Beginner
5
What is a database in MySQL?
Beginner

In 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
In MySQL, a database is a container that holds a collection of related tables, views, stored procedures, and other database objects. You use the `CREATE DATABASE` command to create one.
SQL Snippet
CREATE DATABASE interview_db;
Beginner
6
What are the common data types in MySQL?
Beginner

MySQL 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
MySQL supports several categories of data types: 1. **Numeric**: INT, DECIMAL, FLOAT, DOUBLE. 2. **String**: CHAR, VARCHAR, TEXT, BLOB. 3. **Date and Time**: DATE, DATETIME, TIMESTAMP, YEAR. 4. **Spatial**: GEOMETRY, POINT.
Beginner
7
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
**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 define VARCHAR(10) and store 'ABC', it will only use 3 bytes plus one byte for length prefix. VARCHAR is generally preferred for saving space unless the data length is truly constant (like country codes).
Beginner
8
How do you create a table in MySQL?
Beginner

You use the `CREATE TABLE` statement followed by the table name and column definitions.

Expert Answer
You use the `CREATE TABLE` statement followed by the table name and column definitions.
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
);
Beginner
9
What is a Primary Key?
Beginner

A 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
A 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 have only one primary key.
Beginner
10
What is a Foreign Key?
Beginner

A 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
A 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 orphaned records.
Beginner
11
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
- **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 log. - **TRUNCATE**: A DDL command. It removes all rows from a table by deallocating the pages. It is much faster but cannot use a WHERE clause and resets the AUTO_INCREMENT counter.
Beginner
12
What is a Unique Constraint?
Beginner

A 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
A 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 one NULL value (in MySQL).
Beginner
13
How do you add a new column to an existing table?
Beginner

You use the `ALTER TABLE` statement with the `ADD` clause.

Expert Answer
You use the `ALTER TABLE` statement with the `ADD` clause.
SQL Snippet
ALTER TABLE users ADD phone_number VARCHAR(15);
Beginner
14
What is the auto_increment attribute?
Beginner

The `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
The `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 Primary Key column.
Beginner
15
How do you insert data into a MySQL table?
Beginner

You use the `INSERT INTO` statement.

Expert Answer
You use the `INSERT INTO` statement.
SQL Snippet
INSERT INTO users (username, email) 
VALUES ('john_doe', 'john@example.com');
Beginner
16
What is the WHERE clause used for?
Beginner

The `WHERE` clause is used to filter records that fulfill a specified condition in SELECT, UPDATE, or DELETE statements.

Expert Answer
The `WHERE` clause is used to filter records that fulfill a specified condition in SELECT, UPDATE, or DELETE statements.
SQL Snippet
SELECT * FROM users WHERE username = 'john_doe';
Beginner
17
What is the LIMIT clause?
Beginner

The `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
The `LIMIT` clause is used to specify the number of records to return. This is useful for pagination or limiting the load on the database.
SQL Snippet
SELECT * FROM users LIMIT 10 OFFSET 20;
Beginner
18
How do you sort results in MySQL?
Beginner

You use the `ORDER BY` clause, followed by `ASC` (ascending) or `DESC` (descending).

Expert Answer
You use the `ORDER BY` clause, followed by `ASC` (ascending) or `DESC` (descending).
SQL Snippet
SELECT * FROM users ORDER BY created_at DESC;
Beginner
19
What are Aggregate Functions?
Beginner

Aggregate 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
Aggregate functions perform a calculation on a set of values and return a single value. Common ones include: `COUNT()`, `SUM()`, `AVG()`, `MAX()`, and `MIN()`.
Beginner
20
What is the use of the DISTINCT keyword?
Beginner

The `DISTINCT` keyword is used to return only unique (different) values from a column.

Expert Answer
The `DISTINCT` keyword is used to return only unique (different) values from a column.
SQL Snippet
SELECT DISTINCT country FROM users;
Beginner
21
What is a NULL value?
Beginner

A 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
A 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`.
Beginner
22
How do you update existing data in a table?
Beginner

You use the `UPDATE` statement. Always use a WHERE clause unless you want to update all rows!

Expert Answer
You use the `UPDATE` statement. Always use a WHERE clause unless you want to update all rows!
SQL Snippet
UPDATE users 
SET email = 'new_email@example.com' 
WHERE id = 1;
Beginner
23
How do you delete a database or a table?
Beginner

You use the `DROP` command. This is permanent and cannot be undone.

Expert Answer
You use the `DROP` command. This is permanent and cannot be undone.
SQL Snippet
DROP TABLE users;
DROP DATABASE interview_db;
Beginner
24
What is the LIKE operator?
Beginner

The `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
The `LIKE` operator is used in a WHERE clause to search for a specified pattern in a column. - `%` represents zero, one, or multiple characters. - `_` represents a single character.
SQL Snippet
SELECT * FROM users WHERE username LIKE 'j%';
Beginner
25
What is the default storage engine for MySQL?
Beginner

Since MySQL 5.5, the default storage engine is **InnoDB**. It supports ACID transactions, row-level locking, and foreign keys.

Expert Answer
Since MySQL 5.5, the default storage engine is **InnoDB**. It supports ACID transactions, row-level locking, and foreign keys.
Beginner
26
How do you explain Inner Join in MySQL?
Intermediate

An 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
An 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 common column.
SQL Snippet
SELECT orders.id, users.username 
FROM orders 
INNER JOIN users ON orders.user_id = users.id;
Intermediate
27
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
- **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 right table. - **RIGHT JOIN**: Returns all rows from the right table and matched rows from the left table. If no match is found, NULL values are returned for columns of the left table.
Intermediate
28
What is a Cross Join?
Intermediate

A 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
A 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 generally avoided unless specifically needed for generating combinations.
Intermediate
29
How do you use the GROUP BY clause?
Intermediate

The `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
The `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 aggregate functions.
SQL Snippet
SELECT country, COUNT(id) 
FROM users 
GROUP BY country;
Intermediate
30
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
- **WHERE**: Filters rows *before* they are grouped. - **HAVING**: Filters groups *after* they are formed. It is specifically used with aggregate functions.
Intermediate
31
What is an Index in MySQL?
Intermediate

An 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
An 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 speeds up reading, it slows down writing (INSERT, UPDATE) because the index needs to be updated too.
Intermediate
32
What are the different types of Indexes in MySQL?
Intermediate

1. **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
1. **Primary Index**: Automatically created on the primary key. 2. **Unique Index**: Ensures column values are unique. 3. **Full-Text Index**: Used for text-based searching. 4. **Normal/Simple Index**: Standard B-Tree index. 5. **Spatial Index**: For spatial data types.
Intermediate
33
What is a View in MySQL?
Intermediate

A 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
A 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 existing data.
SQL Snippet
CREATE VIEW active_users AS 
SELECT id, username FROM users WHERE status = 'active';
Intermediate
34
What are Stored Procedures?
Intermediate

A 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
A 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 the code is pre-compiled.
Intermediate
35
What is a Trigger?
Intermediate

A 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
A Trigger is a set of SQL statements that automatically execute or 'fire' when an event (INSERT, UPDATE, or DELETE) occurs on a specific table.
SQL Snippet
CREATE TRIGGER after_user_insert 
AFTER INSERT ON users 
FOR EACH ROW 
INSERT INTO logs (message) VALUES ('New user created');
Intermediate
36
What is a Transaction in MySQL?
Intermediate

A transaction is a unit of work that contains one or more SQL statements. MySQL transactions follow **ACID** properties: Atomicity, Consistency, Isolation, and ...

Expert Answer
A transaction is a unit of work that contains one or more SQL statements. MySQL transactions follow **ACID** properties: Atomicity, Consistency, Isolation, and Durability. They ensure that all operations succeed or none do.
Intermediate
37
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
- **COMMIT**: Saves the changes made during a transaction permanently to the database. - **ROLLBACK**: Undoes all changes made during the current transaction if an error occurs.
Intermediate
38
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
- **Functions**: Must return a single value, can be used in SELECT statements, and only allow input parameters. - **Stored Procedures**: Can return multiple values or none, cannot be used in SELECT statements, and allow IN, OUT, and INOUT parameters.
Intermediate
39
How do you check current running queries in MySQL?
Intermediate

You can use the `SHOW PROCESSLIST` command to see all active connections and their current queries.

Expert Answer
You can use the `SHOW PROCESSLIST` command to see all active connections and their current queries.
SQL Snippet
SHOW PROCESSLIST;
Intermediate
40
What is a Full-Text Search?
Intermediate

Full-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
Full-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()` functions.
SQL Snippet
SELECT * FROM posts 
WHERE MATCH(title, content) AGAINST('database');
Intermediate
41
What is Query Optimization?
Intermediate

Query 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
Query 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 indexes, avoiding `SELECT *`, and analyzing execution plans with `EXPLAIN`.
Intermediate
42
How do you use the EXPLAIN keyword?
Intermediate

The `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
The `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.
SQL Snippet
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
Intermediate
43
What is a Subquery?
Intermediate

A 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
A 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.
SQL Snippet
SELECT * FROM users 
WHERE id IN (SELECT user_id FROM orders);
Intermediate
44
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
- **UNION**: Combines the results of two SELECT statements and removes duplicate rows. - **UNION ALL**: Combines results but includes duplicates. It is faster because it doesn't need to perform a uniqueness check.
Intermediate
45
What is the COALESCE() function?
Intermediate

The `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
The `COALESCE()` function returns the first non-null value in a list. It is very useful for providing default values when data might be NULL.
SQL Snippet
SELECT COALESCE(phone, 'No Phone Provided') FROM users;
Intermediate
46
What is a Composite Index?
Intermediate

A 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
A composite index is an index on multiple columns. It is useful for queries that filter by more than one column in a specific order.
Intermediate
47
How do you find the second highest salary from a table?
Intermediate

You can use subqueries or the `LIMIT` clause with an offset.

Expert Answer
You can use subqueries or the `LIMIT` clause with an offset.
SQL Snippet
SELECT DISTINCT salary 
FROM employees 
ORDER BY salary DESC 
LIMIT 1 OFFSET 1;
Intermediate
48
What is Referential Integrity?
Intermediate

Referential 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
Referential integrity is a database concept that ensures the relationship between tables remains consistent. For example, you cannot delete a row from a 'users' table if it has corresponding records in an 'orders' table (unless cascading is enabled).
Intermediate
49
What are the ON DELETE CASCADE and ON UPDATE CASCADE options?
Intermediate

These 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
These 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 key is updated, automatically update all foreign keys in child rows.
Intermediate
50
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
- **NOW()**: Returns the current date and time (YYYY-MM-DD HH:MM:SS). - **CURDATE()**: Returns only the current date (YYYY-MM-DD).
Intermediate
51
What are the different isolation levels in MySQL?
Advanced

MySQL (InnoDB) supports four isolation levels: 1. **READ UNCOMMITTED**: Lowest isolation, allows dirty reads. 2. **READ COMMITTED**: Prevents dirty reads, but a...

Expert Answer
MySQL (InnoDB) supports four isolation levels: 1. **READ UNCOMMITTED**: Lowest isolation, allows dirty reads. 2. **READ COMMITTED**: Prevents dirty reads, but allows non-repeatable reads. 3. **REPEATABLE READ** (Default): Prevents dirty and non-repeatable reads. Uses Next-Key Locking to prevent phantom reads. 4. **SERIALIZABLE**: Highest isolation, places a lock on every row read, preventing all concurrency issues but slowing down performance significantly.
Advanced
52
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
- **Atomicity**: All operations in a transaction succeed or none do (All or nothing). - **Consistency**: A transaction transforms the database from one valid state to another, maintaining all rules/constraints. - **Isolation**: Concurrent transactions do not interfere with each other. - **Durability**: Once a transaction is committed, it remains so even in the event of a system failure.
Advanced
53
What is Deadlock in MySQL and how to handle it?
Advanced

A 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
A deadlock occurs when two or more transactions mutually hold locks that the others need, causing them to wait forever. InnoDB automatically detects deadlocks and rolls back the transaction that has performed the least amount of change. Developers should handle this by retrying the transaction in the application code.
Advanced
54
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
- **Pessimistic Locking**: Assumes a conflict will happen and locks the records before updating (`SELECT ... FOR UPDATE`). - **Optimistic Locking**: Assumes no conflict will happen. It checks if the data has been modified by someone else before committing (usually using a `version` or `timestamp` column).
Advanced
55
What is a Binary Log (Binlog) in MySQL?
Advanced

The 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
The binary log contains 'events' that describe database changes such as table creation operations or changes to table data. It is crucial for **Replication** and **Point-in-Time Recovery**.
Advanced
56
How does MySQL Replication work?
Advanced

MySQL 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
MySQL 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 binary log into its own **Relay Log** via an I/O thread. 3. The Replica's SQL thread executes the events from the relay log to stay in sync with the source.
Advanced
57
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
- **Statement-Based**: The actual SQL query is sent to replicas. It is efficient but can cause issues with non-deterministic functions like `NOW()`. - **Row-Based**: The actual changes to the data rows are sent. It is more reliable but generates larger log files.
Advanced
58
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
- **Vertical**: Adding more resources (CPU, RAM, SSD) to a single server. - **Horizontal**: Adding more servers to handle the load, often using Read Replicas or Sharding.
Advanced
59
What is Sharding?
Advanced

Sharding 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
Sharding 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 a different server, helping to distribute the load horizontally.
Advanced
60
Explain Query Cache in MySQL.
Advanced

Query 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
Query cache stores the exact text of a SELECT statement together with the corresponding result. If an identical statement is received later, the server retrieves the results from the cache. **Note**: Query cache was deprecated in MySQL 5.7 and removed in 8.0 because it caused performance bottlenecks on multi-core systems.
Advanced
61
What is a Buffer Pool in InnoDB?
Advanced

The 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
The 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 buffer pool allows most data to be read from memory rather than disk.
Advanced
62
What are Hidden Columns in MySQL 8.0?
Advanced

Invisible columns are columns that are not visible to `SELECT *` queries unless explicitly named. They are useful for adding infrastructure columns (like timest...

Expert Answer
Invisible columns are columns that are not visible to `SELECT *` queries unless explicitly named. They are useful for adding infrastructure columns (like timestamps) without breaking existing application code that expects a certain number of columns.
Advanced
63
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
- **InnoDB**: Supports transactions, row-level locking, foreign keys, and is crash-resilient. - **MyISAM**: Does not support transactions, only uses table-level locking, it is faster for read-heavy operations but lacks modern reliability features.
Advanced
64
How to perform a backup of a MySQL database?
Advanced

Common methods include: 1. **mysqldump**: Logical backup (generates SQL file). 2. **MySQL Shell (util.dumpInstance)**: Faster, multi-threaded logical backup. 3....

Expert Answer
Common methods include: 1. **mysqldump**: Logical backup (generates SQL file). 2. **MySQL Shell (util.dumpInstance)**: Faster, multi-threaded logical backup. 3. **Percona XtraBackup**: Physical, hot backup of InnoDB tables without locking.
SQL Snippet
mysqldump -u root -p database_name > backup.sql
Advanced
65
What is slow query log?
Advanced

The 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
The 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 bottlenecks.
Advanced
66
Explain Window Functions in MySQL 8.0.
Advanced

Window 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
Window 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 single output row. Examples: `ROW_NUMBER()`, `RANK()`, `LEAD()`, `LAG()`.
SQL Snippet
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) as rank FROM employees;
Advanced
67
What are Common Table Expressions (CTEs)?
Advanced

A 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
A 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.
SQL Snippet
WITH RegionalSales AS (
  SELECT region, SUM(amount) AS total FROM sales GROUP BY region
)
SELECT * FROM RegionalSales WHERE total > 10000;
Advanced
68
What is JSON support in MySQL?
Advanced

MySQL (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
MySQL (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 support for virtual columns to index JSON data.
SQL Snippet
SELECT info->'$.customer_name' FROM orders;
Advanced
69
Explain the concept of 'Covering Index'.
Advanced

A 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
A 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 fetching the actual data rows (avoiding 'Bookmark Lookup'), which is extremely fast.
Advanced
70
What is the purpose of the Performance Schema?
Advanced

The 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
The 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 times without significantly impacting performance.
Advanced
71
What is an 'Upsert' in MySQL?
Advanced

An 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
An 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 updates it; otherwise, it inserts a new one.
SQL Snippet
INSERT INTO stats (id, count) VALUES (1, 1) 
ON DUPLICATE KEY UPDATE count = count + 1;
Advanced
72
How to secure a MySQL installation?
Advanced

1. 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
1. Run `mysql_secure_installation`. 2. Use strong passwords. 3. Restrict host access for the 'root' user. 4. Enable SSL for connections. 5. Follow the 'Principle of Least Privilege' for user accounts.
Advanced
73
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
- **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 Table**: A subquery in the FROM clause. It is created during query execution and exists only for that query.
Advanced
74
What is 'Ghost Rows' or 'Phantom Read'?
Advanced

A 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
A 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 condition before the first transaction commits. MySQL (InnoDB) prevents this in REPEATABLE READ using Next-Key locking.
Advanced
75
What is adaptive hash index?
Advanced

Adaptive 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
Adaptive Hash Index (AHI) is an InnoDB feature that automatically creates hash indexes for frequently accessed pages in the Buffer Pool. This allows B-Tree pages to behave like hash tables, speeding up lookups for very hot data.
Advanced
76
How to find duplicate records in a table?
Scenario

You can use `GROUP BY` and `HAVING` to find values that appear more than once.

Expert Answer
You can use `GROUP BY` and `HAVING` to find values that appear more than once.
SQL Snippet
SELECT email, COUNT(email) 
FROM users 
GROUP BY email 
HAVING COUNT(email) > 1;
Scenario
77
How to delete duplicate records keeping only one?
Scenario

One way is to use a `JOIN` on the same table and delete rows with a higher ID.

Expert Answer
One way is to use a `JOIN` on the same table and delete rows with a higher ID.
SQL Snippet
DELETE u1 FROM users u1
INNER JOIN users u2 
WHERE u1.id > u2.id AND u1.email = u2.email;
Scenario
78
Write a query to get the nth highest salary.
Scenario

You can use the `LIMIT` clause with an offset (n-1).

Expert Answer
You can use the `LIMIT` clause with an offset (n-1).
SQL Snippet
SELECT DISTINCT salary 
FROM employees 
ORDER BY salary DESC 
LIMIT 1 OFFSET 4; -- 5th highest
Scenario
79
How to select rows with a date in the last 30 days?
Scenario

Use `DATE_SUB()` or `INTERVAL` arithmetic.

Expert Answer
Use `DATE_SUB()` or `INTERVAL` arithmetic.
SQL Snippet
SELECT * FROM orders 
WHERE order_date >= DATE_SUB(NOW(), INTERVAL 30 DAY);
Scenario
80
How to find rows where a column contains only numbers?
Scenario

You can use a Regular Expression.

Expert Answer
You can use a Regular Expression.
SQL Snippet
SELECT * FROM table 
WHERE column_name REGEXP '^[0-9]+$';
Scenario
81
Scenario: Your production database is slow. What are your first steps?
Scenario

1. 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
1. 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. Use `EXPLAIN` on suspect queries to check for missing indexes. 5. Check for table locks or deadlocks.
Scenario
82
How to swap values of two columns in a single UPDATE statement?
Scenario

In MySQL, you can simply set them equal to each other in one line.

Expert Answer
In MySQL, you can simply set them equal to each other in one line.
SQL Snippet
UPDATE table SET col1 = col2, col2 = col1;
Scenario
83
How to copy data from one table to another?
Scenario

Use `INSERT INTO ... SELECT`.

Expert Answer
Use `INSERT INTO ... SELECT`.
SQL Snippet
INSERT INTO archive_users (id, name) 
SELECT id, name FROM users WHERE active = 0;
Scenario
84
How to find the length of the longest string in a column?
Scenario

Use the `MAX()` and `LENGTH()` functions.

Expert Answer
Use the `MAX()` and `LENGTH()` functions.
SQL Snippet
SELECT MAX(LENGTH(description)) FROM products;
Scenario
85
Scenario: You need to store hierarchical data (like categories/subcategories). How do you design it?
Scenario

Common 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
Common 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` values (Fast reads, complex writes). 3. **Path Enumeration**: Stores path like '1/5/12' (Easy to query with LIKE). 4. **Closure Table**: A separate table for all ancestor-descendant relationships (Most flexible).
Scenario
86
How to get the first 3 characters of a string?
Scenario

Use the `LEFT()` or `SUBSTRING()` function.

Expert Answer
Use the `LEFT()` or `SUBSTRING()` function.
SQL Snippet
SELECT LEFT(username, 3) FROM users;
Scenario
87
How to combine first_name and last_name into one column?
Scenario

Use the `CONCAT()` function.

Expert Answer
Use the `CONCAT()` function.
SQL Snippet
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;
Scenario
88
How to find the number of days between two dates?
Scenario

Use the `DATEDIFF()` function.

Expert Answer
Use the `DATEDIFF()` function.
SQL Snippet
SELECT DATEDIFF('2026-12-31', '2026-01-01');
Scenario
89
Scenario: A user reports they can't login, but the database seems fine. What DB-related things do you check?
Scenario

1. 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
1. 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 if the database disk space is full (prevents session creation). 4. Check for slow query performance on the login query.
Scenario
90
How to get the last inserted ID?
Scenario

Use the `LAST_INSERT_ID()` function immediately after the insert.

Expert Answer
Use the `LAST_INSERT_ID()` function immediately after the insert.
SQL Snippet
SELECT LAST_INSERT_ID();
Scenario
91
How to return a random row from a table?
Scenario

Use `ORDER BY RAND() LIMIT 1`. **Warning**: This is slow on large tables as it requires a full table scan.

Expert Answer
Use `ORDER BY RAND() LIMIT 1`. **Warning**: This is slow on large tables as it requires a full table scan.
SQL Snippet
SELECT * FROM users ORDER BY RAND() LIMIT 1;
Scenario
92
How to convert a string to uppercase?
Scenario

Use `UPPER()` or `UCASE()`.

Expert Answer
Use `UPPER()` or `UCASE()`.
SQL Snippet
SELECT UPPER(username) FROM users;
Scenario
93
How to check the version of MySQL you are using?
Scenario

Use the `VERSION()` function or `SELECT @@version;`.

Expert Answer
Use the `VERSION()` function or `SELECT @@version;`.
SQL Snippet
SELECT VERSION();
Scenario
94
Scenario: You want to ensure no two orders are placed for the same product at the exact same millisecond. How?
Scenario

1. 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
1. Use a **Unique Constraint** on a composite of product_id and timestamp (if timestamp has enough precision). 2. Use a **Transaction** with `SERIALIZABLE` isolation level. 3. Use `SELECT ... FOR UPDATE` to lock the product record during the order process.
Scenario
95
How to find all tables in a database?
Scenario

Use `SHOW TABLES;` or query `information_schema.tables`.

Expert Answer
Use `SHOW TABLES;` or query `information_schema.tables`.
SQL Snippet
SHOW TABLES;
Scenario
96
How to rename a table?
Scenario

Use the `RENAME TABLE` statement.

Expert Answer
Use the `RENAME TABLE` statement.
SQL Snippet
RENAME TABLE old_name TO new_name;
Scenario
97
How to grant all privileges to a user on a specific database?
Scenario

Use the `GRANT` statement.

Expert Answer
Use the `GRANT` statement.
SQL Snippet
GRANT ALL PRIVILEGES ON db_name.* TO 'user'@'localhost';
Scenario
98
How to see the structure of a table?
Scenario

Use `DESCRIBE` or `SHOW CREATE TABLE`.

Expert Answer
Use `DESCRIBE` or `SHOW CREATE TABLE`.
SQL Snippet
DESCRIBE users;
Scenario
99
Scenario: You deleted a row by mistake. How do you get it back?
Scenario

1. 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
1. 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 can use `mysqlbinlog` to extract the delete event and reverse it (Point-in-Time Recovery).
Scenario
100
How to empty a table without deleting it?
Scenario

Use `TRUNCATE TABLE`.

Expert Answer
Use `TRUNCATE TABLE`.
SQL Snippet
TRUNCATE TABLE logs;
Scenario
SQL Expert Newsletter

Optimize Your Career!

Join 50,000+ developers receiving weekly tips on MySQL performance tuning, query optimization, and database architecture. Straight to your inbox.