What is a database transaction?
16 May 2023 (Updated 16 May 2023)
In a nutshell
A database transaction is a unit of work performed on a database (e.g., MySQL) that must be treated atomically. That means if you had the following operations:
INSERT INTO users (name) VALUES ('John Doe');
UPDATE users SET email = 'johndoe@gmail.com' WHERE name = 'John Doe';
UPDATE users SET username = 'johndoe' WHERE name = 'John Doe';
If you wrap the above operations into a transaction, then the database would guarantee that either all three operations succeed or none of them do. So if the first two operations succeed, but the third doesn’t, the database will roll back all the operations.
You often need to ensure that either a group of operations all succeed or that none of them do to keep your data in a consistent state.