Transactions, Commits, Rollbacks, and Multi-Step Writes

Commit related writes together or undo them together

🎯 Introduction

By the end of this article, you will be able to commit related writes together or undo them together.


🧾 Why a profile update needs a transaction

Suppose updating a user's city also requires adding a change record. If the city changes but the record is missing, you cannot look up that operation later. A transaction groups related operations: commit only when all succeed, and undo the changes if any step fails.

This article updates user 1 in blog_demo.user. The target record is shown below, with only identity columns:

idusername
1Xiao Ming

We will change this user's city to Chengdu and add a change record. First, create the change-log table:

CREATE TABLE user_change (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    new_city VARCHAR(50) NOT NULL
) ENGINE=InnoDB;

ENGINE=InnoDB at the end of the definition specifies the InnoDB storage engine. A storage engine is the part of MySQL responsible for storing, reading, and writing table data. InnoDB is one such engine and is the default in MySQL 8.4; no separate installation is needed.

We use it because InnoDB supports transactions. If we update the city and then fail to save the change record, the program can execute ROLLBACK to undo the city update too. Both tables whose changes must be undone together need transaction support; configuring only one is insufficient.

The earlier user definition already specified ENGINE=InnoDB, as does user_change above. Query MySQL's table metadata to verify both engines:

SELECT TABLE_NAME, ENGINE
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'blog_demo'
    AND TABLE_NAME IN ('user', 'user_change')
ORDER BY TABLE_NAME;

information_schema.TABLES is MySQL's built-in table metadata catalog. TABLE_SCHEMA is the database name, TABLE_NAME is the table name, and ENGINE is the storage engine. With the course definitions, the result is:

TABLE_NAMEENGINE
userInnoDB
user_changeInnoDB

InnoDB gives the tables transaction support. To group multiple changes into one transaction, you must still start the transaction and explicitly decide whether to commit or roll back, as shown below.


▶️ Start a transaction before making changes

Execute this in a single MySQL client connection:

START TRANSACTION;

The transaction starts, so subsequent writes are not committed individually. Update the city:

UPDATE user SET city = 'Chengdu' WHERE id = 1;

Then save the change record:

INSERT INTO user_change (user_id, new_city) VALUES (1, 'Chengdu');

Neither step has been committed yet. Queries in this connection can see its own writes, but ordinary queries in other connections do not read these uncommitted changes.


✅ Keep the changes with COMMIT

After confirming that both steps succeeded, execute:

COMMIT;

The city and change record are committed together. Reconnecting and querying the user still shows Chengdu. After COMMIT, ROLLBACK cannot undo this operation; you need a new corrective operation or a recovery procedure.


↩️ Undo uncommitted changes with ROLLBACK

Start another transaction and try changing the city to Nanjing:

START TRANSACTION;
UPDATE user SET city = 'Nanjing' WHERE id = 1;

Now decide to abandon the change:

ROLLBACK;

Query again:

SELECT city FROM user WHERE id = 1;

Following the steps in this article produces:

city
Chengdu

The result is still Chengdu. ROLLBACK undoes uncommitted writes in the current transaction, not every past operation.


🪤 A SQL error does not mean earlier changes were undone

If an INSERT fails a constraint check within a transaction, typically only that statement is rolled back; an earlier UPDATE may still be waiting to commit. After any step fails, the application should explicitly execute ROLLBACK rather than catching the error and still issuing COMMIT.

Another easily missed case is an UPDATE that matches no user. It may simply affect zero rows without throwing an error. The application must inspect the result and decide whether this is acceptable or subsequent operations should be canceled.


⚙️ Autocommit and transaction scope

Check whether the current connection uses autocommit:

SELECT @@autocommit;

With the default autocommit configuration:

@@autocommit
1

A typical result is 1: each successful statement commits independently unless a transaction is explicitly started. START TRANSACTION groups subsequent statements until COMMIT or ROLLBACK.

A transaction belongs to one database connection. Separate ordinary calls to a connection pool may use different connections, so starting, updating, and committing cannot be split across them. The Node.js integration article demonstrates borrowing one connection for the entire transaction.

Schema changes such as CREATE TABLE and ALTER TABLE usually cause an implicit commit. Do not mix them into a data modification transaction expecting everything to roll back together. External operations, such as sending email, are not automatically reversed by a database rollback either.


❓ Questions and Answers

Q1: Are larger transactions better?

No. Long-running transactions hold connections and locks. Include only database operations that must complete together; do not wait for user input or external APIs inside a transaction.

Q2: Why can a query inside a transaction see newly updated data?

A connection can read its own uncommitted changes. This does not mean other connections can see them yet.

Q3: What do the four ACID properties mean?

Atomicity means operations succeed or are undone together; consistency means respecting data rules; isolation controls how concurrent operations affect each other; durability preserves committed data according to the database configuration. These properties do not replace correct business checks or backups.


🧪 Exercise

Start a transaction and change the city to Xi'an. Query it in the current connection, roll back, and query again to compare the results.

-- Write your SQL or record your verification results here