SQL Transactions: START TRANSACTION, COMMIT, ROLLBACK
Lesson 16 of 33 in the SQL / MySQL learning path.
How do I make two writes succeed or fail together?
Registering a student for a course is two writes: a row in users and a row in enrollments. If the second write fails, the first should not remain as an account that the roster cannot see. START TRANSACTION begins a unit of work on InnoDB. COMMIT makes both inserts durable. ROLLBACK removes both inserts from the second example, so the practice account never becomes visible. Autocommit is on by default in MySQL, which means a statement outside a transaction is already committed when it finishes.
The script creates the school tables, inserts CS101, then runs two transactions. The first inserts Katherine and her enrollment and commits. The second inserts a rollback student and an enrollment and rolls back. The final reads show Katherine and one enrollment, and they do not show the rolled-back account. Application code wraps the same pair in php-pdo-transactions. DDL such as CREATE TABLE is kept outside the transaction because it forces a commit.
Syntax & Parameters
START TRANSACTION;
INSERT INTO users (...) VALUES (...);
INSERT INTO enrollments (...) VALUES (LAST_INSERT_ID(), ...);
COMMIT;
START TRANSACTION;
INSERT INTO users (...) VALUES (...);
INSERT INTO enrollments (...) VALUES (LAST_INSERT_ID(), ...);
ROLLBACK;
Example
CREATE DATABASE IF NOT EXISTS school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE school;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS courses;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
email VARCHAR(254) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE courses (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
code VARCHAR(16) NOT NULL,
title VARCHAR(160) NOT NULL,
seats SMALLINT UNSIGNED NOT NULL DEFAULT 30,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_courses_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE enrollments (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
course_id INT UNSIGNED NOT NULL,
enrolled_on DATE NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT fk_enrollments_course FOREIGN KEY (course_id) REFERENCES courses (id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO courses (code, title, seats)
VALUES ('CS101', 'Intro to Databases', 30);
START TRANSACTION;
INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Katherine Johnson', 'katherine@school.test', 'sample-hash-not-a-secret', '2026-04-01 09:00:00');
INSERT INTO enrollments (user_id, course_id, enrolled_on, created_at)
VALUES (LAST_INSERT_ID(), 1, '2026-04-01', '2026-04-01 09:00:00');
COMMIT;
START TRANSACTION;
INSERT INTO users (name, email, password_hash, created_at)
VALUES ('Rollback Student', 'rollback@school.test', 'sample-hash-not-a-secret', '2026-04-02 09:00:00');
INSERT INTO enrollments (user_id, course_id, enrolled_on, created_at)
VALUES (LAST_INSERT_ID(), 1, '2026-04-02', '2026-04-02 09:00:00');
ROLLBACK;
SELECT id, name, email FROM users ORDER BY id;
SELECT id, user_id, course_id, enrolled_on FROM enrollments ORDER BY id;
Expected Output
users id | name | email 1 | Katherine Johnson | katherine@school.test 1 row in set enrollments id | user_id | course_id | enrolled_on 1 | 1 | 1 | 2026-04-01 1 row in set rollback@school.test is absent. Both inserts in the second transaction were undone.
Line-by-Line Walkthrough
- CREATE TABLE runs before START TRANSACTION. Data-definition statements cause an implicit commit, so they must not sit inside the unit of work you may still roll back.
- The tables use InnoDB. A MyISAM table commits each insert immediately and ignores ROLLBACK.
- CS101 is inserted and committed on its own, before either transaction, so both enrollment inserts have a real course id of 1.
- START TRANSACTION turns off the one-statement autocommit behavior for the following writes. Other sessions do not see Katherine until COMMIT.
- The first insert creates Katherine. LAST_INSERT_ID() then returns her new user id on this connection, and the enrollment insert uses that id with course 1.
- COMMIT makes the user and the enrollment durable together. A crash after COMMIT keeps both rows.
- The second START TRANSACTION inserts Rollback Student and an enrollment for that new id. Those rows are visible in this session and hidden from other sessions under the default REPEATABLE READ isolation.
- ROLLBACK undoes both inserts of the second transaction. The email rollback@school.test is not in the final users list, and there is no enrollment for that person.
- The final SELECTs show Katherine and one enrollment. The rolled-back pair is absent. Auto-increment does not reuse the id that was rolled back, and the email check is the proof that matters.
- If the enrollment insert had failed, the user insert would still be pending until ROLLBACK. A statement error does not cancel the transaction by itself. Application code in php-pdo-transactions must roll back when either write fails.
Common Pitfalls & Security
A transaction is a promise that the student and the enrollment land together, and it is easy to break that promise by committing too early or by leaving a failed transaction open. Autocommit means a lone INSERT is already permanent. A later ROLLBACK does not undo it. DDL inside the transaction commits the work you thought you could still undo. InnoDB is what makes the promise real. An UPDATE or DELETE inside the transaction still needs WHERE, because COMMIT would save a change that hit every row.
- An UPDATE or DELETE without WHERE is a catastrophe inside a transaction too. COMMIT would store that damage for every student or every enrollment. This script only inserts, and each insert names its columns and values.
- Forgetting START TRANSACTION leaves autocommit on. The user insert commits before the enrollment insert runs, and ROLLBACK cannot remove the account.
- CREATE TABLE, ALTER TABLE, and DROP TABLE force a commit. Keep them before START TRANSACTION, as this script does.
- A failed enrollment insert does not automatically roll back the user insert. Catch the error and execute ROLLBACK, which is the PHP behavior php-pdo-transactions wraps.
- Two sessions that update the same enrollment rows in opposite order can deadlock. One receives an error and must roll back. Retry the whole transaction.
- LAST_INSERT_ID() is per connection. Use it in the same session that just inserted the user. A second connection has its own value and would attach the enrollment to the wrong student.
Best Practices & Modern Standards
Start the transaction, perform the user insert and the enrollment insert, and commit only when both succeed. Roll back the whole unit when either statement fails. Keep all of that on one connection, and keep schema changes outside it. Use InnoDB for users, courses, and enrollments so ROLLBACK is real.
In PHP, turn exceptions on for PDO and call rollBack in the error path. php-pdo-transactions shows that structure. The foreign keys still apply inside the transaction: the enrollment cannot reference a course that does not exist, which is why CS101 is inserted before either unit of work begins.
Real-World Use
Orientation registers a new student and places that student in a course at the same time. The student row belongs in users and the seat belongs in enrollments, with the course already stored in courses. One transaction commits both writes, so the roster never shows a registration without a person and the account list never shows a person the roster lost. The practice path in this lesson rolls the pair back when the registration should not be kept, and the live path commits it.
Frequently Asked Questions
Why are Katherine and her enrollment both still there?
They were written inside the first transaction, and COMMIT ended that transaction successfully. The final SELECT shows her user row and one enrollment for course 1 on 2026-04-01.
Why is the rollback student missing?
The second transaction inserted that user and an enrollment, then ROLLBACK undid both writes. The email rollback@school.test does not appear. A rollback is the whole point of the second example, and both statements in it are ordinary SQL.
What happens if I ROLLBACK without START TRANSACTION?
With autocommit on, each INSERT is already committed. ROLLBACK has no open transaction to undo, and the student remains. Start the transaction before the first write you may need to cancel.
Can I put CREATE TABLE inside the transaction?
MySQL commits the current transaction when you run CREATE, ALTER, or DROP. The script creates the tables first, then starts the transaction that inserts Katherine. Keep that order in application code as well.