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 / 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 / Select Columns, Aliases, Calculations, and DISTINCT

MariaDB Tutorial / Select Columns, Aliases, Calculations, and DISTINCT

Read explicit columns, label results with AS, calculate per-product stock values and understand how DISTINCT treats complete row combinations. Compare expected values and troubleshoot aliases and filters.

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 / Group Results with GROUP BY and Filter Groups with HAVING

MariaDB Tutorial / Group Results with GROUP BY and Filter Groups with HAVING

Create category-level COUNT and SUM reports, distinguish WHERE from HAVING, and reconcile expected groups. Review output grain, ONLY_FULL_GROUP_BY, NULL keys and joined duplicates.

MariaDB Tutorial / Avoid Duplicate Totals When Joining Multiple Tables

MariaDB Tutorial / Avoid Duplicate Totals When Joining Multiple Tables

Trace row multiplication across customer, order, item and product joins. Reconcile correct goods and shipping totals, understand DISTINCT pitfalls and preaggregate details at the order grain.

MariaDB Tutorial / Understand Replication, Lag, Errors, and Failover

MariaDB Tutorial / Understand Replication, Lag, Errors, and Failover

Prepare a two-server local Compose lab and interpret replication status, lag and errors. Observe apply-thread pause/resume behavior and distinguish replication from backup and controlled failover.

MariaDB Tutorial / Troubleshoot Local and Remote MariaDB Connections

MariaDB Tutorial / Troubleshoot Local and Remote MariaDB Connections

Diagnose MariaDB connections by layer, verify local TCP identity and actual table access, and review remote listener, host, firewall and certificate requirements without weakening checks by default.

MariaDB Tutorial / Design Table Relationships with Keys and Foreign Keys

MariaDB Tutorial / Design Table Relationships with Keys and Foreign Keys

Build and inspect customer, product, order and item tables with foreign keys. Verify one-to-many links, reject missing parents and choose deliberate deletion and historical-price policies.

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 / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

MariaDB Tutorial / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

Understand the roles of the MariaDB server and client, the structure of relational data, and the purpose of SQL. Learn how MariaDB relates to MySQL and prepare for a small product-database exercise.