AD JB Toolbox 01 EN

MariaDB Tutorial / Start InnoDB Transactions with COMMIT and ROLLBACK

A transaction groups related data changes into one unit of confirmation. In InnoDB, begin with START TRANSACTION and finish with COMMIT when the result is correct or ROLLBACK when it is not; the statements must share a connection and remain inside the uncommitted transaction boundary.

Define the changes that must succeed together

This exercise changes two balance values to demonstrate confirmation and cancellation without leaving only one side changed. It is a small transaction exercise rather than a complete payment implementation; real financial workflows additionally need a ledger, idempotency, authorization and audit design. Check Target Rows Before UPDATE and DELETE rolls back concrete updates/deletes and Compare Isolation Levels, Locks, and Deadlocks with Two Connections observes concurrent conflicts. The caller-controlled routines in Use Stored Procedures, Functions, and Triggers use the same transaction boundaries.

Control Purpose Boundary
START TRANSACTION Begin a unit in this connection Do not accidentally start over an existing transaction
COMMIT Confirm changes A later ROLLBACK cannot undo that commit
ROLLBACK Cancel uncommitted work Not all connections or DDL
autocommit Default confirmation outside explicit transactions Not sufficient by itself to identify current transaction state

Check the MariaDB documentation for the syntax and conditions used here: start transaction.

Prepare an isolated InnoDB balance table

Connect as course_user to shopcourse and verify the server and database. Check that accounts_35_lab does not exist; otherwise inspect and preserve its contents before deciding whether it is disposable. Run the full setup before beginning either transaction experiment.

USE shopcourse;
CREATE TABLE accounts_35_lab (
 account_id INT PRIMARY KEY,balance DECIMAL(12,2) NOT NULL CHECK(balance>=0)
) ENGINE=InnoDB;
INSERT INTO accounts_35_lab VALUES(1,10000),(2,5000);
SELECT @@autocommit,@@in_transaction;
SHOW CREATE TABLE accounts_35_lab;

Confirm InnoDB and initial balances of 10000.00 for ID 1 and 5000.00 for ID 2. Run the sequence in one connection. A tool that changes connections or automatically commits individual statements changes the procedure’s meaning.

Inspect both updates before rolling back

START TRANSACTION;
SELECT account_id,balance FROM accounts_35_lab
WHERE account_id IN (1,2) ORDER BY account_id FOR UPDATE;
UPDATE accounts_35_lab SET balance=balance-3000
WHERE account_id=1 AND balance>=3000;
SELECT ROW_COUNT() AS debit_rows;

Continue only when debit_rows is 1. If it is zero or an error occurs, issue ROLLBACK; in this connection and do not execute the following credit UPDATE.

UPDATE accounts_35_lab SET balance=balance+3000 WHERE account_id=2;
SELECT ROW_COUNT() AS credit_rows;

credit_rows must also be 1. Otherwise issue ROLLBACK; and stop. Only after both checks succeed, read the balances below.

SELECT account_id,balance FROM accounts_35_lab ORDER BY account_id;

Starting from the untouched fixture, debit_rows and credit_rows must each be 1, with balances 7000.00 and 8000.00. If a step affects the wrong number of rows, stop and ROLLBACK rather than continue the next update. The displayed SQL is a supervised exercise; a program must implement explicit error and row-count branches.

ROLLBACK;
SELECT account_id,balance FROM accounts_35_lab ORDER BY account_id;

The balances return to 10000.00 and 5000.00. Distinguish your own visible uncommitted writes from confirmed changes. If they do not return, inspect connection identity and any automatic or intermediate COMMIT.

Repeat the checked changes and confirm with COMMIT

Repeat the debit, credit and verification blocks in that order, checking each affected-row count. This time, choose the following COMMIT instead of ROLLBACK only when both counts and balances match.

COMMIT;
SELECT account_id,balance FROM accounts_35_lab ORDER BY account_id;

The committed balances are 7000.00 and 8000.00. An ordinary subsequent ROLLBACK no longer restores the original values. Repeat the exercise only through a deliberate fixture reset, and do not equate adding the opposite amount in real data with complete recovery.

Account for errors, locks and implicit commits

An error in one statement does not universally roll back the whole transaction. Handle each error type and the driver’s behavior explicitly. Keep locks short-lived and avoid waiting for user input while holding them.

DDL such as CREATE, ALTER, DROP and TRUNCATE has implicit-commit or other special boundaries. Nontransactional engines do not provide the same cancellation behavior as InnoDB, and an external API call or file transfer cannot be canceled merely by issuing a database ROLLBACK.

Finish open work before resetting the exercise

If execution stopped midway, issue ROLLBACK in the relevant connection and inspect @@in_transaction. Only when this table contains no needed data should it be dropped for a fresh run. Keep structural cleanup outside the rollback experiment.

ROLLBACK;
DROP TABLE shopcourse.accounts_35_lab;
More in This Category
MariaDB Tutorial / Check Target Rows Before UPDATE and DELETE

MariaDB Tutorial / Check Target Rows Before UPDATE and DELETE

Inspect and lock precise target rows, verify UPDATE and DELETE results, and roll back independent InnoDB exercises. Understand affected-row counts, connection requirements and recovery boundaries.

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

Review a SQL dump, restore it into a verified empty database and compare object definitions, rows and goods totals. Handle source-file errors, compatibility and partial-restoration states explicitly.

MariaDB Tutorial / Calculate Running Totals and Compare Rows with LAG and LEAD

MariaDB Tutorial / Calculate Running Totals and Compare Rows with LAG and LEAD

Calculate running totals, LAG and LEAD, then compare ROWS and RANGE with tied timestamps. Verify how filtering before or after accumulation changes a period report.

MariaDB Tutorial / Calculate Date Intervals, Differences, and Display Formats

MariaDB Tutorial / Calculate Date Intervals, Differences, and Display Formats

Compare calendar months, day differences and complete-hour differences with fixed MariaDB examples. Format dates correctly and select full months using explicit interval boundaries.

MariaDB Tutorial / Create Users and Grant Only Required Privileges

MariaDB Tutorial / Create Users and Grant Only Required Privileges

Create a table-scoped MariaDB reader, inspect its real account identity, test allowed reads and denied operations, then verify revocation and review account dependencies before cleanup.

MariaDB Tutorial / Define a Table Structure with CREATE TABLE

MariaDB Tutorial / Define a Table Structure with CREATE TABLE

Define and inspect a MariaDB product-table schema using a complete CREATE TABLE example. Understand defaults, storage settings, IF NOT EXISTS, common errors, and a reset limited to the practice table.

MariaDB Tutorial / Store Dates and Times with DATE, DATETIME, and TIMESTAMP

MariaDB Tutorial / Store Dates and Times with DATE, DATETIME, and TIMESTAMP

Choose DATE, DATETIME, or TIMESTAMP by the meaning of a time value. Run a controlled time-zone comparison, check version-dependent limits and invalid dates, and restore the original session settings.

MariaDB Tutorial / Save Reusable Query Definitions with VIEW

MariaDB Tutorial / Save Reusable Query Definitions with VIEW

Create an INVOKER view for paid-order totals, inspect its definition and observe transaction changes. Review security, updateability, dependencies and the difference between a view and stored result data.

MariaDB Tutorial / Connect Python to MariaDB and Use Parameterized Queries

MariaDB Tutorial / Connect Python to MariaDB and Use Parameterized Queries

Use a complete PyMySQL program to connect, insert, select, commit, and roll back. Keep apostrophes, Unicode, and injection-shaped inputs as values, and restrict dynamic sorting through an identifier allowlist.

MariaDB Tutorial / Insert One Row or Multiple Rows with INSERT

MariaDB Tutorial / Insert One Row or Multiple Rows with INSERT

Practice single-row and multi-row INSERT statements, inspect stored values and defaults, and test duplicate keys, mismatched value counts and required inputs without changing existing product tables.