Using BEGIN, COMMIT, and ROLLBACK in MySQL Transactions
📖 Scenario: You are managing a small online store database. You want to update the stock quantity of a product and record the sale in a sales table. To keep the data safe, you will use transactions to make sure both actions happen together or not at all.
🎯 Goal: Build a MySQL transaction that starts with BEGIN, updates the stock quantity in the products table, inserts a record into the sales table, and then either commits or rolls back the transaction.
📋 What You'll Learn
Create a
products table with columns product_id (INT), product_name (VARCHAR), and stock (INT).Create a
sales table with columns sale_id (INT AUTO_INCREMENT), product_id (INT), and quantity_sold (INT).Start a transaction using
BEGIN.Update the stock of a product by subtracting the sold quantity.
Insert a new sale record into the
sales table.Use
COMMIT to save changes if all queries succeed.Use
ROLLBACK to undo changes if there is an error.💡 Why This Matters
🌍 Real World
Transactions are used in real-world databases to keep data consistent and safe when multiple related changes happen together.
💼 Career
Understanding BEGIN, COMMIT, and ROLLBACK is essential for database administrators and developers to manage data integrity and error recovery.
Progress0 / 4 steps