MySQL Interview Questions for Developers
Try Aihirely for
Smarter Interview Prep
Experience real-time AI support tailored to your Resume.
Boost your confidence and ace every question with
AI Mock Interview.
Question: How does MySQL handle transactions?
Answer:
MySQL handles transactions using the ACID properties, ensuring that database operations are reliable, consistent, and recoverable. A transaction in MySQL is a sequence of one or more SQL operations that are executed as a single unit of work. If any of the operations fail, the entire transaction can be rolled back to maintain data integrity.
ACID Properties:
MySQL uses the ACID p** roperties to manage transactions:
-
Atomicity: Ensures that a transaction is treated as a single unit, meaning either all of its operations are completed successfully, or none of them are applied (rolled back). If an error occurs, the transaction is rolled back, and the database remains unchanged.
-
Consistency: Guarantees that a transaction brings the database from one valid state to another. If the transaction is successful, all constraints and rules (like foreign keys and checks) are preserved.
-
Isolation: Ensures that the operations of one transaction are isolated from others. The changes made by a transaction are not visible to other transactions until the transaction is committed. MySQL offers different isolation levels to control how transactions interact with each other.
-
Durability: Once a transaction is committed, its changes are permanent, even in the event of a system failure. The changes are saved to disk, ensuring data persistence.
Transaction Handling in MySQL:
To work with transactions in MySQL, you can use the following commands:
-
START TRANSACTION (or BEGIN):
- This command is used to begin a new transaction.
- Once a transaction is started, all subsequent SQL statements are part of that transaction until it is either committed or rolled back.
START TRANSACTION; -
COMMIT:
- This command is used to save all changes made during the transaction. After committing a transaction, all changes become permanent.
COMMIT; -
ROLLBACK:
- If an error occurs or you want to undo the changes made during the transaction, you can use
ROLLBACKto revert the database to the state it was in before the transaction began.
ROLLBACK; - If an error occurs or you want to undo the changes made during the transaction, you can use
-
SAVEPOINT:
- This command is used to create a savepoint within a transaction. A savepoint is a point in the transaction to which you can roll back later without affecting the entire transaction.
SAVEPOINT savepoint_name; -
RELEASE SAVEPOINT:
- This command removes a previously defined savepoint.
RELEASE SAVEPOINT savepoint_name; -
SET AUTOCOMMIT:
- In MySQL, you can control the autocommit mode. When autocommit is enabled, each SQL statement is treated as a transaction by itself.
- By default, autocommit is enabled in MySQL, meaning each statement is automatically committed.
- You can disable autocommit to handle multiple statements as a single transaction.
SET AUTOCOMMIT = 0; -- Disable autocommit SET AUTOCOMMIT = 1; -- Enable autocommit
Isolation Levels in MySQL:
MySQL provides different transaction isolation levels to control the visibility of transactions to each other. The isolation level determines how and when the changes made by one transaction become visible to other concurrent transactions. MySQL supports the following isolation levels:
-
READ UNCOMMITTED:
- Transactions can see uncommitted changes made by other transactions.
- Dirty reads: It allows reading data that might later be rolled back by other transactions.
- Lowest level of isolation and may lead to inconsistencies in the data.
-
READ COMMITTED:
- A transaction can only see committed changes made by other transactions.
- Non-repeatable reads: Data read during a transaction may change if another transaction commits changes before the transaction completes.
-
REPEATABLE READ (default in MySQL):
- Ensures that if a transaction reads a row, the value of that row will not change throughout the duration of the transaction, even if other transactions modify it.
- Phantom reads: New rows inserted by other transactions could be seen if the transaction re-executes a query.
- This is the default isolation level in MySQL and is usually sufficient for most applications.
-
SERIALIZABLE:
- The highest isolation level.
- It ensures that no other transactions can access the data being read by the current transaction. It serializes access to data, effectively making transactions execute sequentially.
- Prevents phantom reads, but can lead to performance degradation due to blocking of other transactions.
Syntax for Setting Isolation Levels:
-- Set isolation level for a transaction
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
Transaction Example:
Let’s say you are transferring money between two accounts. Here’s how a transaction might work:
-
Start a transaction:
START TRANSACTION; -
Debit from Account 1:
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; -
Credit to Account 2:
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2; -
Commit the transaction:
COMMIT;
If any error occurs during the process, such as insufficient funds, you can rollback the transaction:
ROLLBACK;
Handling Concurrency with Transactions:
MySQL provides transaction isolation levels that help manage how transactions interact with each other, especially in high-concurrency environments. These levels control the visibility of uncommitted data between transactions, ensuring data consistency while avoiding conflicts like dirty reads, non-repeatable reads, and phantom reads.
Example: Different Isolation Levels
-
READ UNCOMMITTED (Dirty Reads):
- Transaction 1 modifies a row, and Transaction 2 can read the uncommitted data.
-
READ COMMITTED (Non-Repeatable Reads):
- Transaction 1 reads a row, and Transaction 2 commits changes to that row, causing inconsistent results if Transaction 1 reads the row again.
-
REPEATABLE READ (Phantom Reads):
- Transaction 1 reads a set of rows. Transaction 2 inserts new rows, and Transaction 1 reads the set again, but with new rows included.
-
SERIALIZABLE (No Concurrency):
- Transactions are executed one after the other, preventing any conflicts but reducing concurrency and performance.
Summary:
- MySQL handles transactions using the ACID properties (Atomicity, Consistency, Isolation, Durability) to ensure data integrity and reliability.
- Transactions in MySQL are managed with commands like
START TRANSACTION,COMMIT, andROLLBACK. - Isolation levels control the visibility of uncommitted changes across concurrent transactions and help manage concurrency issues like dirty reads, non-repeatable reads, and phantom reads.
- MySQL provides a default isolation level of REPEATABLE READ, but you can adjust this based on the requirements of your application.
Question: Explain the AUTO_INCREMENT feature in MySQL.
Answer:
The AUTO_INCREMENT feature in MySQL is used to automatically generate a unique, sequential value for a column whenever a new record is inserted into a table. This feature is commonly used for primary key columns to ensure that each new row gets a unique identifier without needing the user to manually assign a value. Typically, the AUTO_INCREMENT column is set as the primary key of the table.
Key Features of AUTO_INCREMENT:
-
Automatic Generation of Unique Values:
- When you insert a row into the table without specifying a value for the
AUTO_INCREMENTcolumn, MySQL automatically assigns the next available integer value to that column.
- When you insert a row into the table without specifying a value for the
-
Sequential Values:
- The values assigned to an
AUTO_INCREMENTcolumn are sequential. By default, the sequence starts at1and increments by1for each new row. - The value is unique for each row, ensuring no duplicates in the
AUTO_INCREMENTcolumn.
- The values assigned to an
-
No Need to Manually Specify Values:
- When inserting data, you do not need to specify a value for the
AUTO_INCREMENTcolumn. MySQL will take care of it. - Example:
INSERT INTO table_name (column2, column3) VALUES ('value2', 'value3');—theAUTO_INCREMENTcolumn will be filled automatically.
- When inserting data, you do not need to specify a value for the
-
Customizing the Starting Value:
- You can customize the starting point of the
AUTO_INCREMENTsequence by specifying a value when creating the table or by altering the table afterward. - The default starting value is
1, but you can set it to another number if needed.
- You can customize the starting point of the
-
Handling Gaps:
- Gaps in the sequence of
AUTO_INCREMENTvalues may occur if a row is deleted, or if a transaction fails after generating anAUTO_INCREMENTvalue but before inserting the row. However, MySQL will not reuse these gaps. - The next
AUTO_INCREMENTvalue will be the next sequential integer, and the gap will remain.
- Gaps in the sequence of
-
AUTO_INCREMENTand Primary Keys:- The
AUTO_INCREMENTfeature is typically used for columns that are defined as primary keys. The value generated byAUTO_INCREMENTensures that the primary key column has unique values for each row.
- The
-
Limits:
- The maximum value for an
AUTO_INCREMENTcolumn depends on the data type of the column. For example:INTcan hold values from1to2,147,483,647(signed) or0to4,294,967,295(unsigned).BIGINTcan hold much larger values, from-9,223,372,036,854,775,808to9,223,372,036,854,775,807(signed).TINYINT,SMALLINT,MEDIUMINT, etc., have respective maximum values based on their size.
- The maximum value for an
-
Resetting the
AUTO_INCREMENTValue:- You can reset the
AUTO_INCREMENTcounter for a table, typically after truncating the table or deleting all rows. - Example:
This resets the nextALTER TABLE table_name AUTO_INCREMENT = 1;AUTO_INCREMENTvalue to1(or another specified value).
- You can reset the
Syntax for Using AUTO_INCREMENT:
-
Creating a Table with an
AUTO_INCREMENTColumn:CREATE TABLE users ( user_id INT AUTO_INCREMENT, username VARCHAR(100), email VARCHAR(100), PRIMARY KEY (user_id) );- In this example, the
user_idcolumn is anAUTO_INCREMENTcolumn. When a new record is inserted into theuserstable, MySQL will automatically assign a unique, sequential value to theuser_idcolumn.
- In this example, the
-
Inserting Data Without Specifying the
AUTO_INCREMENTValue:INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com');- You do not need to specify a value for
user_id. MySQL will automatically assign the next available value.
- You do not need to specify a value for
-
Specifying the Next Value for
AUTO_INCREMENT:ALTER TABLE users AUTO_INCREMENT = 1001;- This command sets the next
AUTO_INCREMENTvalue for theuserstable to1001.
- This command sets the next
-
Retrieving the Last Inserted
AUTO_INCREMENTValue:- You can use the
LAST_INSERT_ID()function to retrieve the last automatically generated value for anAUTO_INCREMENTcolumn.
SELECT LAST_INSERT_ID(); - You can use the
Example Usage:
Step 1: Creating the Table
CREATE TABLE products (
product_id INT AUTO_INCREMENT,
product_name VARCHAR(100),
price DECIMAL(10, 2),
PRIMARY KEY (product_id)
);
In this example, product_id is an AUTO_INCREMENT column, meaning each time you insert a new row, MySQL will automatically generate a unique value for product_id.
Step 2: Inserting Data Without Specifying product_id
INSERT INTO products (product_name, price) VALUES ('Laptop', 999.99);
INSERT INTO products (product_name, price) VALUES ('Smartphone', 699.99);
- After the first insertion,
product_idwill automatically be1, and after the second insertion, it will automatically be2, without the need for manual intervention.
Step 3: Checking the product_id
SELECT * FROM products;
Output:
+------------+----------------+-------+
| product_id | product_name | price |
+------------+----------------+-------+
| 1 | Laptop | 999.99|
| 2 | Smartphone | 699.99|
+------------+----------------+-------+
Step 4: Resetting the AUTO_INCREMENT Value
ALTER TABLE products AUTO_INCREMENT = 1;
- This command will reset the
AUTO_INCREMENTvalue to1, meaning the next insertion will assignproduct_id = 1(if no rows exist).
Common Use Cases for AUTO_INCREMENT:
- Primary Key Generation: Most commonly used to generate unique IDs for rows, especially when those IDs are used as primary keys in relational tables.
- Seamless Record Insertion: Simplifies record insertion, as there’s no need to manually specify a unique value for each row.
- Tracking Sequential Data: Useful for scenarios where you need to keep track of records in a specific order, like invoice numbers, order IDs, etc.
Summary:
- The
AUTO_INCREMENTfeature in MySQL automatically generates unique, sequential values for a column whenever a new record is inserted. - It is typically used for primary key columns to ensure each row has a unique identifier.
- You can customize the starting value and reset the counter if needed.
- It simplifies data insertion by eliminating the need to manually assign unique values to certain columns.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as MySQL interview questions, MySQL interview experiences, and details about various MySQL job positions. Click here to check it out.
