Menu

Database Transactions Explained: How a Payment Is All or Nothing
📰

Database Transactions Explained: How a Payment Is All or Nothing

DEV Community: mysql·Dilip V P·10 days ago
#4A44q9u5
#devtomysql#devto#dev#mysql#alex
Long article (1085 words) — no AI summary yet.
Reading 0:00
15s threshold

Alex pays twenty dollars for his pizza. The bank takes the money out of his account, and then the power goes out, before the money reaches the pizza shop. When the power comes back, Alex has his twenty dollars again. The payment was a transaction, and a transaction is all or nothing. This article shows how the database keeps that promise.

The video tells the same story in five minutes. This is the written version, with the SQL.

One payment, two changes

Both accounts are at the same bank, in one MySQL database:

CREATE TABLE accounts ( owner VARCHAR ( 64 ) NOT NULL , balance INT NOT NULL , PRIMARY KEY ( owner ) ) ENGINE = InnoDB ;

INSERT INTO accounts VALUES ( 'Alex' , 100 ) , ( 'Pizza Shop' , 500 ) ;

Enter fullscreen mode

Exit fullscreen mode

A payment looks like one step, but it is two changes:

UPDATE accounts SET balance = balance - 20 WHERE owner = 'Alex' ; UPDATE accounts SET balance = balance + 20 WHERE owner = 'Pizza Shop' ;

Enter fullscreen mode

Exit fullscreen mode

Each change alone

If…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.