Back to articles
Database Transactions: ACID Properties in Plain English

Database Transactions: ACID Properties in Plain English

via Dev.toAtlas Whoff

What Is a Transaction? A transaction is a group of database operations that either all succeed or all fail together. BEGIN ; UPDATE accounts SET balance = balance - 100 WHERE id = 1 ; UPDATE accounts SET balance = balance + 100 WHERE id = 2 ; COMMIT ; If the second update fails, the first one rolls back automatically. Money doesn't disappear into the void. ACID: The Four Guarantees Atomicity "All or nothing." BEGIN ; INSERT INTO orders ( user_id , total ) VALUES ( 42 , 9900 ); INSERT INTO order_items ( order_id , product_id , qty ) VALUES ( LASTVAL (), 7 , 2 ); UPDATE inventory SET stock = stock - 2 WHERE product_id = 7 ; COMMIT ; -- If any statement fails, ALL are rolled back No partial orders. No inventory decremented without an order. No order without items. Consistency "Data must be valid before and after." Constraints prevent invalid states: -- Balance can never go negative ALTER TABLE accounts ADD CONSTRAINT positive_balance CHECK ( balance >= 0 ); BEGIN ; UPDATE accounts SET bal

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles