Popular Searches
Popular Course Categories
Popular Courses

Introduction to Database Transactions

Introduction to Database Transactions

Transactions and Concurrency Control

Introduction to Database Transactions in MySQL

Course: MySQL Training

Topic: Introduction to Database Transactions

Course Link: MySQL Training Course at JustAcademy

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Database Transactions

A database transaction is a logical unit of work that consists of one or more database operations performed together. These operations may include inserting new records, updating existing records, deleting data, or reading information. A transaction is designed to keep data accurate and consistent, especially when several related operations must succeed together.

In MySQL, transactions are commonly used in applications such as banking systems, e-commerce websites, booking platforms, inventory management systems, payroll software, and customer management applications.

For example, when a customer transfers money from one bank account to another, the system must deduct money from the sender's account and add the same amount to the receiver's account. If the deduction succeeds but the deposit fails, the database could contain an incorrect balance. A transaction allows both operations to be committed together or rolled back when an error occurs.

1.1 Simple Definition

A database transaction is a sequence of operations treated as one logical unit of work. The transaction either completes successfully and commits its changes, or its uncommitted changes can be rolled back.

1.2 Why Are Transactions Important?

  • They help maintain data accuracy and consistency.
  • They prevent incomplete related operations from being committed as a successful unit.
  • They allow changes to be committed or rolled back.
  • They help coordinate concurrent database operations.
  • They support reliable financial and business applications.
  • They reduce the risk of inconsistent data when an operation fails partway through.

1.3 Real-World Example

Imagine an online shopping application that processes a customer order. The system may need to create an order, record the payment, and reduce the available inventory. If the inventory update fails after the order and payment records have been written, the application must have a suitable recovery strategy to prevent inconsistent business records.

Transactions can help coordinate these database changes when they are performed within the same transactional database transaction. However, payment gateways, external services, and other systems may require additional techniques, such as compensating actions or distributed workflow patterns.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Define database transactions and explain their purpose.
  • Understand the ACID properties of transactions.
  • Identify transaction boundaries in SQL operations.
  • Use START TRANSACTION, COMMIT, and ROLLBACK.
  • Understand autocommit behavior in MySQL.
  • Explain the difference between committed and uncommitted changes.
  • Understand savepoints and partial rollback.
  • Recognize the role of transactional storage engines such as InnoDB.
  • Identify common transaction errors and apply best practices.
  • Understand how transactions interact with concurrent users and database locks.

3. Understanding the Basic Transaction Process

A transaction usually begins before a group of related SQL operations. After executing the required statements, the application either commits the changes when the operation succeeds or rolls back the uncommitted changes when an error occurs.

3.1 Transaction Workflow

  1. Begin: Start a transaction using START TRANSACTION or another supported transaction-starting statement.
  2. Execute operations: Perform the required INSERT, UPDATE, DELETE, or other transactional SQL statements.
  3. Validate results: Check whether the operations completed successfully and whether business rules were satisfied.
  4. Commit or roll back: Use COMMIT to make the transaction's changes permanent, or ROLLBACK to undo uncommitted changes.

3.2 General Syntax

START TRANSACTION;

-- Execute related SQL statements
UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;

UPDATE accounts
SET balance = balance + 500
WHERE account_id = 2;

-- Save the changes if everything succeeds
COMMIT;

This example demonstrates the basic syntax. In production code, the application must also verify that both updates affect the intended accounts and that the sender has sufficient funds before committing.

3.3 What Happens If an Operation Fails?

If a statement fails, the application should determine whether the transaction can safely continue. For an error that invalidates the business operation, the application should roll back the transaction. Some MySQL errors roll back only the failing statement, while others may cause the entire transaction to be rolled back. The application should not assume every error automatically rolls back the whole transaction.

START TRANSACTION;

UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;

-- If a later operation fails, handle the error
-- and roll back when appropriate.
ROLLBACK;

The ROLLBACK statement undoes the transaction's uncommitted changes for transactional tables. It cannot reverse changes that were already committed, and it does not undo operations on nontransactional tables in the same way.

4. The ACID Properties of Database Transactions

ACID is a group of four properties that describe reliable transaction processing: Atomicity, Consistency, Isolation, and Durability.

Property Meaning Example
Atomicity A transaction's operations are treated as one logical unit: the intended unit succeeds, or its uncommitted changes are rolled back. A money transfer must not commit only the debit while leaving out the corresponding credit.
Consistency A transaction should preserve the database's defined rules and constraints. An account balance must satisfy the application's balance rules and any applicable database constraints.
Isolation Concurrent transactions are controlled so that their interactions follow the configured isolation level. Two customers updating inventory should not cause an invalid final quantity.
Durability Once a transaction is committed, its changes are designed to survive failures according to the database's durability guarantees and configuration. A committed order should remain recorded after a server restart.

4.1 Atomicity

Atomicity means that related database operations should not be treated as independently successful pieces of one logical transaction. If the transaction cannot complete as intended, the uncommitted changes can be rolled back.

Example: transferring money involves deducting the amount from one account and adding it to another. Both updates should be part of the same transaction so that one does not commit without the other.

4.2 Consistency

Consistency means that transactions should preserve valid database states by respecting defined rules, constraints, and application logic. These rules may include primary keys, foreign keys, unique constraints, check constraints where supported, and business validations.

For example, an application may require that an order references an existing customer. A foreign key can help enforce that relationship at the database level.

4.3 Isolation

Isolation describes how concurrent transactions interact. MySQL provides different transaction isolation levels that control visibility and locking behavior. The exact results depend on the selected isolation level, the storage engine, and the SQL statements being executed.

For example, when multiple users attempt to purchase the last item in stock, the database must coordinate their operations so the application does not incorrectly confirm more purchases than available inventory allows.

4.4 Durability

Durability means that committed changes are intended to survive a database crash or restart. Actual durability behavior also depends on the storage engine, server configuration, hardware, and storage reliability. Backups and recovery procedures remain important even when transactions are used.

5. Transaction Support in MySQL

MySQL supports transactions through storage engines that implement transactional behavior. The most commonly used transactional storage engine is InnoDB.

5.1 What Is InnoDB?

InnoDB is a MySQL storage engine that supports transactions, row-level locking in many operations, foreign keys, crash recovery, and other features important for reliable application data.

5.2 Check a Table's Storage Engine

SHOW TABLE STATUS
FROM company_db
LIKE 'accounts';

Replace company_db with the database name and accounts with the table name. The output includes the table's storage engine.

You can also inspect a table definition:

SHOW CREATE TABLE accounts;

5.3 Create a Table Using InnoDB

CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    account_holder VARCHAR(100) NOT NULL,
    balance DECIMAL(12,2) NOT NULL
) ENGINE = InnoDB;

This creates an account table using InnoDB. For a real financial application, additional constraints, validation, auditing, access control, and appropriate precision and business rules would be needed.

5.4 Why Does the Storage Engine Matter?

  • InnoDB supports transactional COMMIT and ROLLBACK behavior.
  • It supports foreign key constraints.
  • It provides concurrency control through locking and multiversion concurrency control mechanisms.
  • It offers crash-recovery features.
  • Nontransactional storage engines do not provide the same rollback guarantees for their data changes.

Important: If a transaction modifies both transactional and nontransactional tables, rolling back the transaction does not necessarily undo changes made to the nontransactional tables.

6. Starting a Transaction in MySQL

The START TRANSACTION statement begins a transaction. MySQL also supports BEGIN as a transaction-starting statement in this context.

6.1 Using START TRANSACTION

START TRANSACTION;

INSERT INTO accounts (account_id, account_holder, balance)
VALUES (101, 'Amit Sharma', 5000.00);

COMMIT;

The INSERT is committed when the transaction reaches COMMIT, assuming the statement succeeds and the table uses a transactional storage engine.

6.2 Using BEGIN

BEGIN;

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 101;

COMMIT;

BEGIN can be used to start a transaction in SQL scripts. In stored programs, be aware that MySQL also uses BEGIN ... END to delimit compound statements, so use the correct syntax for the context.

6.3 Starting a Transaction with a Consistent Snapshot

InnoDB supports transaction options that affect isolation and read behavior. For example, START TRANSACTION WITH CONSISTENT SNAPSHOT can be used in supported contexts to establish a consistent read view at transaction start. Its effect depends on the isolation level and server behavior.

START TRANSACTION WITH CONSISTENT SNAPSHOT;

SELECT *
FROM accounts;

COMMIT;

Use advanced transaction options only when their behavior is understood and appropriate for the application's concurrency requirements.

7. Understanding COMMIT

The COMMIT statement successfully ends the current transaction and makes its changes permanent according to the storage engine's transaction guarantees.

7.1 COMMIT Syntax

COMMIT;

7.2 Example of Committing an Update

START TRANSACTION;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 101;

COMMIT;

After the transaction is committed, the balance update is no longer an uncommitted change that can be undone with a normal transaction rollback.

7.3 Verify the Result

SELECT account_id, account_holder, balance
FROM accounts
WHERE account_id = 101;

This query displays the current account record so that you can verify the result of the transaction.

7.4 When Should COMMIT Be Used?

  • When all required statements have succeeded.
  • When application-level validation has passed.
  • When the intended business operation is complete.
  • When the application is ready to make the changes visible as committed data.

8. Understanding ROLLBACK

The ROLLBACK statement cancels the current transaction's uncommitted changes for transactional tables. It is used when an operation fails or when validation shows that the changes should not be saved.

8.1 ROLLBACK Syntax

ROLLBACK;

8.2 Example of Rolling Back an Update

START TRANSACTION;

UPDATE accounts
SET balance = balance - 500
WHERE account_id = 101;

ROLLBACK;

If the update succeeds and the table is transactional, the rollback cancels the uncommitted balance change.

8.3 Compare the Balance Before and After

SELECT account_id, balance
FROM accounts
WHERE account_id = 101;

The query returns the balance currently stored in the database. If the transaction was rolled back successfully, the uncommitted subtraction will not be reflected.

8.4 Important Limitations of ROLLBACK

  • It cannot undo a transaction that has already been committed.
  • It does not reliably reverse changes made to nontransactional tables.
  • Some statements cause implicit commits in MySQL.
  • Errors can have different rollback effects depending on the statement and transaction state.
  • It does not automatically undo actions performed by an external payment gateway or another independent system.

9. Autocommit in MySQL

MySQL normally operates with the autocommit system variable enabled. When autocommit is ON, each successful statement outside an explicitly managed transaction is committed automatically.

9.1 Check Autocommit Status

SELECT @@autocommit;

A result of 1 means autocommit is enabled, while 0 means it is disabled for the current session.

9.2 Example with Autocommit Enabled

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 101;

When autocommit is enabled and the statement executes outside an explicit transaction, a successful update is normally committed automatically.

9.3 Disable Autocommit for the Current Session

SET autocommit = 0;

With autocommit disabled, changes are not automatically committed after every statement. The session can commit or roll back changes explicitly. Use this setting carefully because open transactions can hold locks and consume resources.

9.4 Re-enable Autocommit

SET autocommit = 1;

Changing autocommit from OFF to ON commits an active transaction in MySQL. Therefore, do not switch it on casually when you intend to roll back pending changes.

9.5 Autocommit Compared with Explicit Transactions

Feature Autocommit ON Explicit Transaction
Typical behavior Each standalone statement is committed automatically. Related statements are grouped into one transaction.
COMMIT needed Not usually needed for each standalone statement. Used to save the transaction's changes.
ROLLBACK use Cannot undo a statement that has already been committed. Can undo uncommitted changes to transactional tables.
Common use Independent simple database operations. Multi-step operations that must succeed or fail together.

10. Practical Example: Bank Account Transfer

A bank transfer is a classic example of a transaction because it requires related changes to two accounts.

10.1 Create the Accounts Table

CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    account_holder VARCHAR(100) NOT NULL,
    balance DECIMAL(12,2) NOT NULL
) ENGINE = InnoDB;

10.2 Insert Sample Data

INSERT INTO accounts (account_id, account_holder, balance)
VALUES
(1, 'Amit Sharma', 10000.00),
(2, 'Neha Verma', 5000.00);

10.3 Start the Transfer Transaction

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000.00
WHERE account_id = 1
  AND balance >= 1000.00;

UPDATE accounts
SET balance = balance + 1000.00
WHERE account_id = 2;

COMMIT;

This demonstrates the transaction structure, but it is not a complete production-safe transfer implementation. In a real application, the code must verify that the debit updated exactly one row and that the recipient account exists and was updated. If either check fails, the transaction must be rolled back instead of committed.

10.4 A Safer Transfer Pattern in Application Logic

  1. Start a transaction.
  2. Lock or safely update the sender's account using an appropriate concurrency strategy.
  3. Verify that the sender exists and has sufficient funds.
  4. Update the sender's balance and verify the affected-row count.
  5. Update the receiver's balance and verify the affected-row count.
  6. Commit only when every required step succeeds.
  7. Roll back on failure and report the error to the application.

For robust financial applications, use carefully tested transaction logic, appropriate locking, consistent lock ordering, audit records, and application-level safeguards against duplicate requests.

10.5 Check the Final Balances

SELECT account_id, account_holder, balance
FROM accounts
ORDER BY account_id;

If the transfer succeeds, the sender's balance decreases by 1000.00 and the receiver's balance increases by the same amount. The total of the two balances remains unchanged, assuming no fees or other operations.

11. Practical Example: Order Creation and Inventory Update

An e-commerce system may need to create an order and reduce inventory in the same transaction. This example illustrates the basic approach using two InnoDB tables.

11.1 Create the Products Table

CREATE TABLE products (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    stock_quantity INT NOT NULL
) ENGINE = InnoDB;

11.2 Create the Orders Table

CREATE TABLE orders (
    order_id INT PRIMARY KEY AUTO_INCREMENT,
    product_id INT NOT NULL,
    quantity INT NOT NULL,
    order_status VARCHAR(30) NOT NULL,
    FOREIGN KEY (product_id) REFERENCES products(product_id)
) ENGINE = InnoDB;

11.3 Insert a Sample Product

INSERT INTO products (product_id, product_name, stock_quantity)
VALUES (1, 'Wireless Mouse', 20);

11.4 Begin the Transaction

START TRANSACTION;

UPDATE products
SET stock_quantity = stock_quantity - 2
WHERE product_id = 1
  AND stock_quantity >= 2;

INSERT INTO orders (product_id, quantity, order_status)
VALUES (1, 2, 'Confirmed');

COMMIT;

This basic example shows how inventory and order creation can be grouped together. However, the application must check that the inventory update affected exactly one row. If no row was updated, the order must not be inserted and committed. A robust implementation should also handle duplicate requests and any failure during order creation.

11.5 Verify the Data

SELECT * FROM products;
SELECT * FROM orders;

The inventory quantity and order record should reflect the same successful operation. If any required step fails, the application should roll back the transaction.

12. Savepoints in MySQL Transactions

A savepoint marks a position within a transaction. It allows a transaction to roll back some of its changes without necessarily cancelling the entire transaction.

12.1 Create a Savepoint

START TRANSACTION;

UPDATE accounts
SET balance = balance - 100
WHERE account_id = 1;

SAVEPOINT after_debit;

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 2;

ROLLBACK TO SAVEPOINT after_debit;

COMMIT;

In this example, the second update is rolled back to the savepoint, but the earlier debit remains part of the transaction and is committed. This is intentionally not a valid completed money transfer; it demonstrates why savepoints must be used carefully when business operations require all-or-nothing behavior.

12.2 Remove a Savepoint

RELEASE SAVEPOINT after_debit;

The RELEASE SAVEPOINT statement removes a savepoint. Releasing a savepoint does not commit the transaction.

12.3 Savepoint Commands

Command Purpose
SAVEPOINT savepoint_name Creates a savepoint within the current transaction.
ROLLBACK TO SAVEPOINT savepoint_name Reverts changes made after the savepoint while keeping the transaction active.
RELEASE SAVEPOINT savepoint_name Removes a savepoint without committing the transaction.

13. Transaction Isolation Levels

Transaction isolation levels control how concurrent transactions observe one another's changes. MySQL InnoDB supports the standard isolation-level names READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE, with behavior determined by the storage engine and the specific operations used.

Isolation Level General Description Considerations
READ UNCOMMITTED Allows the weakest isolation and can expose uncommitted changes through some reads. Dirty reads may occur.
READ COMMITTED Ordinary consistent reads generally see committed data as of each read. Repeated reads may return different committed results.
REPEATABLE READ InnoDB's default isolation level in common MySQL configurations; consistent reads within a transaction generally use a stable snapshot. Locking reads and writes have additional locking behavior.
SERIALIZABLE Provides stricter isolation by making concurrent transactions behave more like a serial execution. Can increase blocking and reduce concurrency.

13.1 Check the Current Isolation Level

SELECT @@transaction_isolation;

In MySQL versions that support this variable, it returns the session's transaction isolation level. Some older versions use different variable names, so consult the documentation for your installed version if necessary.

13.2 Set the Session Isolation Level

SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

This sets the isolation level for subsequent transactions in the current session, subject to MySQL's transaction rules. Isolation choices should be based on application correctness and concurrency requirements, not selected solely for speed.

14. Concurrency, Locking, and Transaction Safety

Multiple users may read or modify the same data at the same time. InnoDB uses mechanisms such as row-level locking and multiversion concurrency control to coordinate many concurrent operations.

14.1 Why Locking Is Important

Consider two customers attempting to purchase the last available product. If both applications read the same stock quantity and then independently subtract one, an unsafe implementation could oversell the product. A properly designed conditional update or locking strategy helps prevent this outcome.

14.2 Conditional Inventory Update

START TRANSACTION;

UPDATE products
SET stock_quantity = stock_quantity - 1
WHERE product_id = 1
  AND stock_quantity >= 1;

-- Application must verify that exactly one row was updated.
-- Commit only if the update succeeded and the remaining
-- business operations also succeed.

COMMIT;

The conditional UPDATE is an important safeguard, but the example omits application-side row-count validation. The application must roll back if no row was updated or another required operation fails.

14.3 Deadlocks

A deadlock can occur when two or more transactions wait for locks held by each other. InnoDB detects many deadlocks and rolls back a transaction to break the cycle. Applications should be prepared to retry a transaction that fails due to a deadlock when the operation is safe to retry.

14.4 Reduce Locking Problems

  • Keep transactions as short as practical.
  • Access tables and rows in a consistent order.
  • Create suitable indexes for frequently used search conditions.
  • Avoid waiting for user input or external services while holding database locks.
  • Handle deadlocks and lock timeouts in application code.
  • Use the isolation level appropriate for the task.

15. Implicit Commits and Transaction Limitations

Not every SQL statement behaves like a normal transactional DML statement. MySQL performs implicit commits for many statements that change database structure or server configuration. This can end an active transaction unexpectedly if such statements are issued inside the transaction workflow.

15.1 Examples of Statements That May Cause Implicit Commits

Many DDL statements, including common uses of CREATE TABLE, ALTER TABLE, and DROP TABLE, cause implicit commits. The exact rules depend on the statement and the MySQL version.

15.2 Avoid Mixing DDL with Business Transactions

-- Avoid treating this as one atomic business transaction.
START TRANSACTION;

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 1;

CREATE TABLE temporary_report (
    report_id INT PRIMARY KEY
);

ROLLBACK;

The DDL statement may cause an implicit commit. As a result, the preceding update may already be committed and may not be undone by the later ROLLBACK.

15.3 Other Important Limitations

  • COMMIT and ROLLBACK affect the current transaction, not previously committed transactions.
  • Transactions cannot automatically reverse external API calls, messages, or payments.
  • Long-running transactions may retain locks and increase resource usage.
  • Rollback guarantees depend on using a transactional storage engine.
  • Application-level business rules still need to be validated.

16. Common Transaction Errors and Troubleshooting

Problem Possible Cause Solution
ROLLBACK does not undo a change The change was already committed or the table is nontransactional. Check transaction boundaries and storage engine.
Only one part of an operation succeeds Related statements were not included in the same transaction or an operation was committed too early. Group the related statements and commit only after validation.
Transaction remains open COMMIT or ROLLBACK was not issued. Explicitly finish the transaction and review application error handling.
Deadlock error Concurrent transactions acquired locks in conflicting orders. Keep transactions short, use consistent access order, and implement safe retries.
Lock wait timeout A transaction is waiting too long for a conflicting lock. Inspect blocking transactions, shorten transaction duration, and review indexes.
Unexpected commit occurs An implicit-commit statement was executed or autocommit behavior was misunderstood. Review statement semantics and autocommit settings.
Unexpected data changes The WHERE clause matched more rows than intended. Test with SELECT, validate affected-row counts, and use appropriate keys and constraints.
Insufficient funds or negative inventory Business validation or concurrency control is incomplete. Use conditional updates, constraints where appropriate, locking, and application checks.

17. Best Practices for Database Transactions

17.1 Keep Transactions Short

Long transactions can hold locks, increase contention, and delay other users. Perform only the necessary database work inside a transaction and avoid unnecessary waiting.

17.2 Commit Only After Validation

Check that every required operation succeeds before committing. An application should inspect affected-row counts and handle SQL exceptions rather than blindly committing after executing statements.

17.3 Roll Back on Failure

Use application error handling to issue ROLLBACK when the operation cannot safely continue. Make sure connection cleanup and transaction state are handled correctly.

17.4 Use Transactional Tables

Use InnoDB for data that requires transaction rollback, foreign keys, and reliable concurrent updates. Confirm that all tables participating in a transaction use appropriate transactional storage engines.

17.5 Avoid Unnecessary Nested Transaction Assumptions

MySQL does not provide independently nestable transactions in the way some developers may expect. Savepoints provide partial rollback points inside a transaction, but starting another transaction can affect the existing transaction boundary.

17.6 Handle Errors and Retries Carefully

Deadlocks and some transient failures may require retrying a transaction. A retry should repeat the entire logical operation safely, and the operation should be designed to avoid duplicate side effects.

17.7 Use Constraints to Protect Data

Primary keys, unique constraints, foreign keys, NOT NULL constraints, and appropriate check constraints can help preserve data integrity. Application validation and database constraints work together; neither should be treated as a substitute for all the other safeguards.

17.8 Test Before Production

Test commit, rollback, concurrency, deadlocks, error paths, and recovery behavior in a controlled environment. Verify both successful and unsuccessful transaction outcomes.

18. Practical Exercises

  1. Create an InnoDB table named employees with employee ID, name, and salary columns.
  2. Insert a new employee within a transaction and commit the operation.
  3. Update an employee's salary and roll back the change.
  4. Create an accounts table and demonstrate a transaction involving two account updates.
  5. Use SELECT to verify the data before and after COMMIT.
  6. Use SELECT to verify that an uncommitted update is cancelled by ROLLBACK.
  7. Check the current autocommit setting using SELECT @@autocommit;.
  8. Create a savepoint, perform multiple updates, and roll back to the savepoint.
  9. Check the transaction isolation level and change it for a test session.
  10. Demonstrate why an implicit-commit DDL statement should not be mixed casually with a business transaction.
  11. Design an inventory update that prevents stock from becoming negative.
  12. Simulate an error in a multi-step transaction and implement suitable rollback handling.

19. Mini Project: Employee Salary Transfer Between Departments

Project Objective: Practice transaction handling by transferring an employee's department assignment while recording the change in an audit table.

19.1 Create the Employee Table

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    department_id INT NOT NULL
) ENGINE = InnoDB;

19.2 Create the Audit Table

CREATE TABLE employee_department_audit (
    audit_id INT PRIMARY KEY AUTO_INCREMENT,
    employee_id INT NOT NULL,
    old_department_id INT NOT NULL,
    new_department_id INT NOT NULL,
    changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB;

19.3 Example Transaction

START TRANSACTION;

UPDATE employees
SET department_id = 20
WHERE employee_id = 101;

INSERT INTO employee_department_audit
    (employee_id, old_department_id, new_department_id)
VALUES
    (101, 10, 20);

COMMIT;

This example demonstrates grouping the employee update and audit insert in a transaction. A production implementation should first verify the employee exists, confirm the previous department value, and ensure the UPDATE affected the intended row. The audit values should be based on the actual old and new values rather than hard-coded assumptions.

19.4 Project Tasks

  • Insert sample employee records.
  • Change an employee's department within a transaction.
  • Insert an audit record as part of the same transaction.
  • Roll back the transaction deliberately and confirm neither change is committed.
  • Commit a valid change and verify both tables.
  • Improve the implementation to retrieve the actual previous department and validate affected-row counts.

20. Interview Questions and Answers

Q1. What is a database transaction?

A database transaction is a logical unit of work that groups one or more operations and allows them to be committed or rolled back as appropriate.

Q2. What does ACID stand for?

ACID stands for Atomicity, Consistency, Isolation, and Durability.

Q3. What is the purpose of COMMIT?

COMMIT ends the current transaction and makes its changes permanent according to the storage engine's transaction guarantees.

Q4. What is the purpose of ROLLBACK?

ROLLBACK cancels the current transaction's uncommitted changes for transactional tables.

Q5. What is autocommit in MySQL?

Autocommit is a session setting that normally commits each successful standalone statement automatically when enabled.

Q6. Which MySQL storage engine commonly supports transactions?

InnoDB is the commonly used MySQL storage engine that supports transactions, foreign keys, and crash recovery.

Q7. Can ROLLBACK undo a committed transaction?

No. Once a transaction has been committed, a normal ROLLBACK cannot undo it. A separate compensating operation or a recovery process may be required.

Q8. What is a savepoint?

A savepoint marks a position within a transaction so that selected changes made after that point can be rolled back without necessarily cancelling the entire transaction.

Q9. What is transaction isolation?

Transaction isolation controls how concurrent transactions interact and what data changes they can observe.

Q10. What is a deadlock?

A deadlock occurs when transactions wait for locks held by one another in a way that prevents them from progressing. InnoDB detects many deadlocks and rolls back one of the transactions.

Q11. What happens when a DDL statement causes an implicit commit?

The active transaction may be committed automatically, meaning a later ROLLBACK cannot undo the changes that were committed before the rollback.

Q12. Why should a transaction be kept short?

Short transactions reduce the time locks are held, improve concurrency, and lower the risk of blocking and resource contention.

Q13. Can a transaction span multiple tables?

Yes. A transaction can modify multiple tables, provided the operations and storage engines support the required transactional behavior.

Q14. Does a transaction automatically reverse an external payment?

No. A MySQL transaction controls database operations within its transactional scope. External payment systems require separate error-handling and compensation mechanisms.

Q15. How can you check autocommit?

SELECT @@autocommit;

21. Quick Revision Checklist

  • A transaction groups related database operations into one logical unit.
  • ACID stands for Atomicity, Consistency, Isolation, and Durability.
  • InnoDB supports transactional behavior in MySQL.
  • START TRANSACTION begins a transaction.
  • COMMIT saves the transaction's changes.
  • ROLLBACK cancels uncommitted changes to transactional tables.
  • Autocommit is normally enabled by default.
  • Savepoints support partial rollback within a transaction.
  • Isolation levels affect how concurrent transactions interact.
  • Deadlocks and lock timeouts require appropriate error handling.
  • Some MySQL statements cause implicit commits.
  • Transactions cannot automatically reverse external system operations.
  • Use validation, constraints, suitable indexes, and short transactions.
  • Test transaction success and failure paths before production use.

22. Conclusion

Database transactions are essential for maintaining reliable and consistent data in MySQL applications. They allow developers to group related operations and decide whether to commit or roll back their changes. Understanding ACID properties, InnoDB, autocommit, transaction boundaries, savepoints, isolation levels, and locking behavior helps developers build safer database-driven applications.

For dependable transaction processing, always validate business rules, check the results of important SQL statements, handle errors appropriately, and commit only when the complete operation succeeds. Correct transaction design is especially important in banking, e-commerce, booking systems, inventory management, and other applications where incomplete updates can cause serious inconsistencies.

Explore the MySQL course: MySQL Training Course at JustAcademy

Register for a course demo: Book Your JustAcademy Course Demo

Visit JustAcademy: https://www.justacademy.co/

Official MySQL Documentation: MySQL COMMIT and ROLLBACK | InnoDB Transaction Model | InnoDB Transaction Isolation Levels

whatsapp