MariaDB Transaction – Helpful Guide

In this MariaDB tutorial, we will learn about MariaDB Transaction. Additionally, we will cover the following topics.

  • MariaDB Transaction
  • MariaDB Transaction Rollback Example
  • MariaDB Transaction Log
  • MariaDB Transaction Isolation Level
  • MariaDB Transaction Timeout
  • MariaDB Transaction Rollback On Error
  • MariaDB Transactional DDL
  • MariaDB Transaction Example
  • MariaDB Transaction Alter Table
  • MariaDB Statements That Cause An Implicit Commit
  • MariaDB Transaction Autocommit
  • MariaDB Kill Transaction
  • MariaDB Transaction Query

MariaDB Transaction

Here, we will learn about the basics of MariaDB Transaction.

MariaDB Transactions are a sequence of operations performed in a group. Each group works separately, and will not terminate until its operations are complete.

A single failure within the group will fail the entire transaction, which will not affect the database.

A database maintains consistency by following certain properties before and after a transaction. These properties are called ACID properties.

  • Atomicity – It guarantees the success of all operations by aborting and rolling back changes in the event of failure.
  • Consistency – In this way, the database ensures that changes are applied on a successful transaction.
  • Isolation – It enables independent transaction operations.
  • Durability – It ensures that even the failure of the system will not affect the persistence of the transaction.

A MariaDB Transaction goes through various stages, starting with the START TRANSACTION or BEGIN statement followed by COMMIT and ROLLBACK statements.

  • START TRANSACTION/BEGIN – Initiates a transaction
  • COMMIT – Saves the changes on the data durig the transaction
  • ROLLBACK – Ends the transaction while destroying all the changes.

Note – If the transaction is successful, then COMMIT acts, and in case of failure of a transaction, ROLLBACK acts.

Transactions in MariaDB can also be performed with options such as SAVEPOINT and LOCK TABLES.

  • SAVEPOINT creates a point to restore to with ROLLBACK.
  • LOCK TABLES prevents modifications to tables during sessions.

The general structure of a transaction consists of the following things.

  • Begins with START TRANSACTION/BEGIN statement
  • Inserting one or more commands/operations
  • Inserting statements for checking errors
  • Inserting ROLLBACK statements in case of error being discovered.
  • Finally COMMIT statement to apply changes to successful operations.

Read: MariaDB Union Operator

MariaDB Transaction Rollback Example

Here, we will learn about MariaDB ROLLBACK, its syntax, and an example

Rollback in MariaDB is the process of undoing transactions that have not been saved in the database. It can only undo the changes since the last commit.

The syntax of the Rollback Statement in MariaDB is given below.

ROLLBACK;

MariaDB ROLLBACK has no parameters or arguments in its syntax.

It is mostly used after a set of statements leading to changes in the data since the last commit.

Example illustrating the working of ROLLBACK statement in MariaDB.

The table used i.e. cities before any changes are shown below.

MariaDB Cities Table
MariaDB Cities Table
START TRANSACTION;
DELETE FROM cities
WHERE city_id > 5;

Here, we are removing the data of the cities table using the DELETE statement where city_id is greater than 5 in MariaDB.

After running the DELETE Statement on the cities table in MariaDB.

MariaDB DELETE Statement
MariaDB DELETE Statement

Here, we can see that the records of the cities table have been removed in MariaDB.

Now, we will run MariaDB ROLLBACK STATEMENT to see what happens.

ROLLBACK;
MariaDB ROLLBACK Example
MariaDB ROLLBACK Example

Here, you can see that the records of the cities table which was previously deleted are again present in the cities table in MariaDB.

Read: MariaDB Select Statement

MariaDB Transaction Log

In this, we will learn about the MariaDB Transaction Log, how to enable it and display it on MariaDB Client-Server.

To view all the Transactions performed in MariaDB, you need to view the General Query Log which contains the log of each and every MariaDB query.

The General query log is a collection of each and every MariaDB Query received from the client, as well as each client connect and disconnect. It grows quickly as it is a record of every query received by the server.

The general query log is disabled by default. To enable the general query log, set the general_log to 1 using SET GLOBAL.

Before setting general_log to 1, let us check the general query log by typing the below command.

SELECT * FROM mysql.general_log\G
MariaDB Log All Queries Disabled
MariaDB Log All Queries Disabled

To get the log of all transactions, you need to type the following command.

SET GLOBAL general_log=1;

This is how you can enable the general query log but this can only be disabled for a connection by a user with super privilege by changing the SQL_LOG_OFF variable to 1.

After setting the value of general_log to 1, we need to select the General Query Log Output Destination.

The General Log Query can be written in 2 ways.

  • Writing General Log Query to a file
  • Writing General Log Query to a table

Writing General Log Query to a file

By default, the general log query is output to a file. Although, it can be changed dynamically by setting the log_output system variable to FILE using SET GLOBAL.

To change the General Log Output Destination to a FILE, you need to type the following command.

SET GLOBAL log_output='FILE';
MariaDB Transaction Log In File
MariaDB Transaction Log In File

Writing General Log Query to a table

By default, the general log query is output to a file. Although, it can be changed dynamically by setting the log_output system variable to TABLE using SET GLOBAL.

To change the General Log Output Destination to a TABLE, you need to type the following command.

SET GLOBAL log_output='TABLE';
MariaDB Transaction Log In Table
MariaDB Transaction Log In Table

After setting the General Log Output Destination to either a FILE or TABLE, you need to type the following command to get all the queries in a log.

SELECT * FROM mysql.general_log\G
MariaDB Transaction Log
MariaDB Transaction Log

Here, you can find the log of all MariaDB queries which contains the log of all MariaDB transactions too.

This is how we can get the MariaDB Transaction Log.

Read: MariaDB Join with Examples

MariaDB Transaction Isolation Level

Here, we will learn about MariaDB Transaction Isolation Level, its types with an example.

A transaction’s isolation level determines how it is isolated from other transactions. It is the process of separating data or resource modifications carried out by different transactions. There are several levels of isolation that allow concurrency side effects, such as dirty reads or phantom reads.

According to the SQL standard, there are four isolation levels.

  • Read Uncommitted
  • Read Committed
  • Repeatable Read
  • Serializable

In addition, the isolation level implemented in MySQL and the isolation level implemented in SQL Server are somewhat different at the same level.

The default isolation level in MariaDB is a repeatable read. Transaction isolation is achieved by locks, which is the isolation level in the transaction characteristics (ACID).

Read Uncommitted – Transactions in MariaDB at this isolation level can see the execution results of other uncommitted transactions. Since its performance is not much better than other levels, this isolation level is rarely used in practical applications. Uncommitted data is also known as dirty data.

Read Committed – Most database systems (except MySQL) use this level of isolation by default. In other words, it satisfies the simple definition of isolation: a transaction can only see changes made by a committed transaction.

A transaction only sees changes made to it by a committed transaction, because the transaction satisfies the simple definition of isolation. It also supports the so-called Nonrepeatable Read, since other instances of the same transaction may have new commits during that instance’s processing, so the same selection may produce different results.

Repeatable Read – MySQL’s default transaction isolation level guarantees that multiple instances of the same transaction will see the same row of data when reading data concurrently. Theoretically, though, this leads to a second thorny problem i.e. Phantom Reading.

The term ‘hallucination‘ refers to causing the user to find “hallucination” rows after reading a range of data rows, another transaction inserting new rows, and the user re-reading the range of data rows. With MVCC (Multiversion Concurrency Control), InnoDB and Falcon solve this problem.

Serializable – In the highest isolation level, transactions must be sorted to make it impossible to conflict with each other. This solves the hallucination problem. Each row of reading data is locked with a shared lock. It may lead to a large number of timeouts and lock competitions at this level.

Here, we have learned about MariaDB Transaction Isolation Level, its types with an example.

Read: MariaDB Select Into

MariaDB Transaction Timeout

Here, we will learn about the basics of MariaDB Transaction Timeout.

In MariaDB, there are settings to manage wait_timeout and interactive_timeout, which close connections after a set amount of inactivity.

wait_timeout – When a connection is active, the server waits for it to become active before closing it. An interactive connection’s session will be initialized either by the global value or by the interactive_timeout value, when it starts, depending on whether the connection is non-interactive in MariaDB.

interactive_timeout – Before closing an interactive connection (a connection using mysql_real_connect() CLIENT_INTERACTIVE option), the server waits for it to become active for a specific number of seconds in MariaDB.

These are, however, set to have a long waiting period by default. A shorter timeout and more granular control could be beneficial in cases where transactions may be started but not committed or rolled back so that locks are not held for an excessive amount of time.

Three new variables were introduced by MariaDB to deal with this situation.

  • idle_transaction_timeout – for all transactions
  • idle_write_transaction_timeout  write transactions called idle_readwrite_transaction_timeout.
  • idle_readonly_transaction_timeout – for read transactions

idle_transaction_timeout – Waiting time in seconds for the server to kill the connection when there are no transactions. If it is set to zero by default, then the connections are never killed.

An example for MariaDB Transaction idle_transaction_timeout is given below.

SET SESSION idle_transaction_timeout = 60;
BEGIN;
USE US_data;
Select * from cities;

##wait for 61 seconds

Select * from cities; 

Here, we are providing the idle_transaction_timeout a certain value and performing some operations, and again waiting for some duration that is greater than the idle_transaction_timeout and displaying the result as given below.

MariaDB Transaction idle_transaction_timeout
MariaDB Transaction idle_transaction_timeout

idle_write_transaction_timeout When idle read-write transactions exist, the server waits for them for a certain amount of time before killing the connection. If it is set to zero by default, then the connections are never killed.

An example for MariaDB Transaction idle_transaction_timeout is given below.

SET SESSION idle_write_transaction_timeout = 60;
BEGIN;
SELECT * FROM cities; 

##wait for 61 seconds

INSERT INTO cities(cname) VALUES
   ('New Jersey')

SELECT * FROM cities; 

##wait for 61 seconds

SELECT * FROM cities; 

Here, we are providing the idle_write_transaction_timeout a certain value and performing some operations, and again waiting for some duration that is greater than the idle_write_transaction_timeout and displaying the result as given below.

MariaDB Transaction idle_write_transaction_timeout
MariaDB Transaction idle_write_transaction_timeout

idle_readonly_transaction_timeout – The number of seconds the server waits for idle read-only transactions before killing the connection. If it is set to zero by default, then the connections are never killed.

An example for MariaDB Transaction idle_transaction_timeout is given below.

SET SESSION idle_readonly_transaction_timeout = 30;
BEGIN;
Select * from cities;

##wait for 31 seconds

Select * from cities; 

Here, we are providing the idle_readonly_transaction_timeout a certain value and performing some operations, and again waiting for some duration that is greater than the idle_readonly_transaction_timeout and displaying the result as given below.

MariaDB Transaction idle_readonly_transaction_timeout
MariaDB Transaction idle_readonly_transaction_timeout

Here, we have learned about the basics of MariaDB Transaction Timeout.

Read: MariaDB Case Statement

MariaDB Transaction Error On Rollback

Here, we will learn about MariaDB Transaction Error On Rollback.

Error while performing a Rollback in MariaDB can only happen because of two reasons given below.

  • Commit Has Been Performed
  • Rollback On Statements Which Causes Implicit Commit

Commit Has Been Performed – During a transaction, if we commit the changes done on a MariaDB transaction then we can’t perform a rollback on it. Even if we try to rollback the changes, it would result in it in an error or unexpected results.

Example for Rollback after the commit has been performed.

MariaDB After Alter table
MariaDB Table Before Commit
INSERT INTO cities(state_name) VALUES
    -> ('California');

SELECT * FROM cities;

Here, we are inserting the records in a table i.e. ‘California‘ in the state_name column in the cities table.

MariaDB Commit
MariaDB Commit

Now, we will try to rollback the changes using the below statement in MariaDB.

ROLLBACK;

SELECT * FROM cities;
MariaDB Rollback After Commit
MariaDB Rollback After Commit

Here, we can see that even after the Rollback Statement, there are no changes as the commit has been already performed in MariaDB.

Rollback On Statements Which Causes Implicit Commit – During a transaction if we make the changes using the statements that cause an implicit commit on a MariaDB transaction then we can’t perform a rollback on it. Even if we try to rollback the changes, it would result in it in an error or unexpected results.

Example for ALTER TABLE illustrating the implicit commit property.

MariaDB Before Alter Table
MariaDB Before Alter Table
ALTER TABLE cities
     DROP COLUMN city_id;

Here, we are removing one of the columns from a table i.e. city_id from the cities table.

MariaDB Alter Table
MariaDB Alter Table

Now, we will try to rollback the changes using the below statement.

ROLLBACK;
MariaDB After Alter table
MariaDB After Rollback

Here, we have learned about MariaDB Transaction Error On Rollback.

Read: MariaDB Window functions

MariaDB Transactional DDL

Here, we will learn about the MariaDB Transaction DDL.

The data definition language (DDL) statements are used to describe the database structure. A data definition language describes how data should exist in the database, so statements like CREATE TABLE or ALTER TABLE fall under the DDL.

DDL commands include CREATE, ALTER, and DROP statements. These commands are used to CREATE, ALTER, OR DROP the database objects (Tables, Views, Users).

Most of the DDL statements are implicitly committed at the end of any statement or after the execution of a statement.

Here, the DDL statements list implicitly ends any transaction that is active in the current session, just as if you had committed the session before executing the statement.

Most of these statements cause implicit commits after execution. The intention is to handle each such statement as a separate transaction.

Data definition language (DDL) statements that define or modify database objects.

S. No.StatementsDescription
1.ALTER EVENTModifies the characteristics of an existing event in MariaDB.
2.ALTER FUNCTIONChanges the characteristics of a stored function in MariaDB.
3.ALTER PROCEDUREChanges the characteristics of a stored procedure in MariaDB.
4.ALTER SERVERChanges/modifies the server information in MariaDB.
5.ALTER TABLEUsed to add, drop/delete, or modify columns in a table in MariaDB.
6.ALTER TABLESPACEUsed to add a new data file or drop a data file from a tablespace in MariaDB.
7.ALTER VIEWModifies the definition of an existing view in MariaDB.
8.CREATE DATABASEUsed to create a new database in MariaDB.
9.CREATE EVENTUsed to create a new event in MariaDB.
10.CREATE FUNCTIONUsed to create a new stored function in MariaDB.
11.CREATE INDEXUsed to create a new index in MariaDB.
12.CREATE PROCEDUREUsed to create a new stored Procedure in MariaDB.
13.CREATE ROLECreates one or more roles in MariaDB.
14.CREATE SERVERUsed to create an entry in mysql.servers table in MariaDB.
15.CREATE SPATIAL REFERENCE SYSTEMUsed to create Spatial Reference System in MariaDB.
16.CREATE TABLEUsed to create a new table in a database in MariaDB.
17.CREATE TABLESPACEUsed to create a new tablespace in MariaDB.
18.CREATE TRIGGERUsed to create triggers in MariaDB.
20.CREATE VIEWUsed to create a view of a table in MariaDB.
21.DROP DATABASEUsed to drop all tables in a particular database and delete the database in MariaDB.
22.DROP EVENTUsed to drop or delete events completely in MariaDB.
23.DROP FUNCTIONUsed to drop a stored function in MariaDB.
24.DROP INDEXUsed to drop/delete completely an index.
25.DROP PROCEDUREUsed to drop a stored procedure in MariaDB.
26.DROP ROLEUsed to drop an already existing role in MariaDB.
27.DROP SERVERUsed to drop a server in MariaDB.
28.DROP TABLEUsed to drop a table from a database in MariaDB.
29.DROP TABLESPACEUsed to drop an already existing tablespace in MariaDB.
30.DROP TRIGGERUsed to drop an already existing trigger in MariaDB.
31.DROP VIEWUsed to drop a view of a table in MariaDB.
32.INSTALL PLUGINUsed to install an individual plugin from a specified library in MariaDB.
33.RENAME TABLEUsed to change the name of a table in MariaDB.
34.TRUNCATE TABLEUsed to delete all rows from a table similar to Delete statement without Where clause in MariaDB.
35.UNINSTALL PLUGINUsed to install an already installed individual plugin in MariaDB.

Example for ALTER TABLE illustrating the implicit commit property.

MariaDB Before Alter Table
MariaDB Before Alter Table
ALTER TABLE cities
    -> DROP COLUMN city_id;

Here, we are removing one of the columns from a table i.e. city_id from the cities table.

MariaDB Alter Table
MariaDB Alter Table

Now, we will try to rollback the changes using the below statement.

ROLLBACK;
MariaDB After Alter table
MariaDB After Rollback

If the TEMPORARY keyword is used with CREATE TABLE and DROP TABLE statements, no transaction is committed. But with temporary tables, other operations such as ALTER TABLE and CREATE INDEX do cause a commit.

In addition to the absence of implicit commits, such statements cannot be rolled back, resulting in a violation of transactional atomicity.

For example, if you create a temporary table and roll back the transaction, the table remains in existence.

Here, we have learned about the MariaDB Transaction DDL.

Read: MariaDB Row_Number Tutorial

MariaDB Transaction Example

Here, we will learn about the MariaDB Transaction, syntax, and an example.

A MariaDB Transaction goes through various stages, starting with the START TRANSACTION or BEGIN statement followed by COMMIT and ROLLBACK statements.

  • START TRANSACTION/BEGIN – Initiates a transaction
  • COMMIT – Saves the changes on the data durig the transaction
  • ROLLBACK – Ends the transaction while destroying all the changes.

Note – If the transaction is successful, then COMMIT acts, and in case of failure of a transaction, ROLLBACK acts.

Transactions in MariaDB can also be performed with options such as SAVEPOINT and LOCK TABLES.

  • SAVEPOINT creates a point to restore to with ROLLBACK.
  • LOCK TABLES prevents modifications to tables during sessions.

The general structure of a transaction consists of the following things.

  • Begins with START TRANSACTION/BEGIN statement
  • Inserting one or more commands/operations
  • Inserting statements for checking errors
  • Inserting ROLLBACK statements in case of error being discovered.
  • Finally COMMIT statement to apply changes to successful operations.

Usually, MariaDB Transaction is initiated using the START TRANSACTION statement in MariaDB. Likewise, BEGIN WORK is an alternate keyword for START TRANSACTION. If the transaction is successful, then COMMIT acts, and in case of failure of a transaction, ROLLBACK acts.

The overall syntax can therefore be written as follows.

START TRANSACTION;
{trans_charact {, trans_charact}…}
Trans charact:{

WITH CONSISTENT SNAPSHOT | READ WRITE | READ ONLY

}

BEGIN {WORK}

COMMIT {WORK} {AND {NO} CHAIN} {{NO} RELEASE}

ROLLBACK {WORK} {AND {NO} CHAIN} {{NO} RELEASE}

SET autocommit = (1, 0);

Here:

  • MariaDB START TRANSACTION, where the synonym of the keyword can be BEGIN WORK.
  • COMMIT command to save the current MariaDB transaction and make the changes permanent.
  • ROLLBACK command to rollback the current transaction and undo its changes.
  • SET autocommit to activate or deactivate the mode of auto-commit for the current transaction.
  • By default, MariaDB server automatically commits changes to the database and permanently.
  • The parser interprets the BEGIN [WORK] command as the initial part of the BEGIN…END code block within whole stored programs like stored procedures, functions, and triggers.
  • WORK is optional and it supports ROLLBACK and COMMIT methods.
  • RELEASE & CHAIN provides more control on the transaction’s completion.

Example illustrating the working of START TRANSACTION statement.

Here, we are using a table i.e. US_City.

MariaDB US_City Table
MariaDB US_City Table
START TRANSACTION;
INSERT INTO US_City
(City, State, Country) 
VALUES
('El Paso', NULL, 'US'),
('Las Vegas', NULL, NULL);
COMMIT

Here, we are inserting records in the cities table and committing the changes.

MariaDB Transaction Example
MariaDB Transaction Example

Here, we can see that the changes have been implemented in the US_City table.

MariaDB Transaction Alter Table

Here, we will learn about the MariaDB Transaction Alter Table.

By using the ALTER TABLE statement, you can add, modify, or delete columns from a table. Renaming a table is also possible with the MariaDB ALTER TABLE statement.

The syntax of Alter Table in MariaDB is given below.

ALTER tableName
alter statement1...
alter statement2...;

There are some statements in MariaDB that cause an implicit commit which results at the end of any transaction which was active in the current session. One of them is Alter Table in MariaDB, it implicitly ends any transaction that is active in the current session, just as if you had committed the session before executing the statement.

So, due to implicit commit in Alter Table in MariaDB, it can’t be rolled back. Due to its implicit commit, every statement that has an implicit commit can be treated as a small transaction.

This is all about MariaDB Transaction Alter Table.

Read: MariaDB DateTime Tutorial

MariaDB Statements That Cause An Implicit Commit

Here, we will learn about the MariaDB Statements That Cause An Implicit Commit.

There are some statements in MariaDB that cause an implicit commit which results at the end of any transaction which was active in the current session.

Here, the statements list implicitly ends any transaction that is active in the current session, just as if you had committed the session before executing the statement.

Most of these statements cause implicit commits after execution. The intention is to handle each such statement as a separate transaction.

Data definition language (DDL) statements that define or modify database objects. You can view the list of statements that cause an implicit commit in the MariaDB Transactional DDL topic.

If the TEMPORARY keyword is used with CREATE TABLE and DROP TABLE statements, no transaction is committed. But with temporary tables, other operations such as ALTER TABLE and CREATE INDEX do cause a commit.

In addition to the absence of implicit commits, such statements cannot be rolled back, resulting in a violation of transactional atomicity.

For example, if you create a temporary table and roll back the transaction, the table remains in existence.

Here, we have learned about the MariaDB Statements That Cause An Implicit Commit.

MariaDB Transaction Autocommit

Here, we will learn about the basics of MariaDB Transaction Autocommit.

The Autocommit in MariaDB means that when a statement is completed, the method commit is automatically invoked on that statement. This effectively makes every SQL statement a transaction. A commit happens when a statement finishes, or when the next statement is executed, whichever occurs first.

By applying the following query statements, we can force the MariaDB server to automatically commit the modifications.

SET autocommit = 1;
MariaDB Enable Autocommit
MariaDB Enable Autocommit

Or we can also use the below statement to enable autocommit in MariaDB.

SET autocommit = ON;
MariaDB Enabling Autocommit
MariaDB Enable Autocommit

And by applying the following query statements, we can also force the MariaDB server not to automatically commit the modifications.

SET autocommit = 0;
MariaDB Disable Autocommit
MariaDB Disable Autocommit

Or we can also use the below statement to disable autocommit in MariaDB.

SET autocommit = OFF;
MariaDB Disabling Autocommit
MariaDB Disable Autocommit

Here, we have learned about the basics of MariaDB Transaction Autocommit.

Read: MariaDB Date + Examples

MariaDB Kill Transaction

Here, we will learn about How to Kill MariaDB Transaction.

To terminate a MariaDB Transaction, we need to use the KILL statement which terminates the connection associated with a thread or query id.

The syntax of the KILL statement in MariaDB is given below.

KILL <thread_id| query_id>;

In the process of killing a query, firstly you need to know the running thread or active queries. We can do this using two methods, then we can terminate any Query Id or Thread Id using the KILL statement. The two methods are listed below.

  • By Using PROCESSLIST
  • By Using GENERAL QUERY LOG

By Using PROCESSLIST:

The syntax for viewing the PROCESSLIST is given below.

SHOW [FULL] PROCESSLIST;

If you don’t use the FULL keyword, only 100 characters of the query will be displayed in the info field.

To view the running active threads/queries, we need to run the following command.

SHOW PROCESSLIST;
MariaDB Transaction ProcessList
MariaDB Transaction ProcessList

Now, we need to terminate the query using the KILL Statement by typing the following command.

KILL (9);
MariaDB Kill Transaction
MariaDB Kill Transaction

Here, ‘9‘ is the query id that we want to terminate, and after running this statement, the query will be terminated.

Note – Here, the ERROR 1927 can be seen which is a MariaDB Internal Error and should be ignored.

By Using GENERAL QUERY LOG:

To view all the transactions performed in MariaDB, you need to view the General Query Log which contains the log of each and every MariaDB query.

You can refer to the MariaDB Transaction Log topic to access the General Query Log in MariaDB. And using the thread id or query id, you can kill the MariaDB transaction.

Here, we have learned about How to Kill MariaDB Transaction.

Read: MariaDB DATEDIFF Function

MariaDB Transaction Queries

Here, we will learn about the various MariaDB Transaction Queries.

There are commonly used Queries related to MariaDB Transaction, they are as follows,

  • START TANSACTION
  • COMMIT
  • ROLLBACK

START TRANSACTION – Usually, MariaDB Transaction is initiated using the START TRANSACTION statement in MariaDB. Likewise, BEGIN WORK is an alternate keyword for START TRANSACTION. However, it doesn’t function inside the stored programs since BEGINEND encompasses the blocks of code.

The overall syntax can be shown as follows.

START TRANSACTION;

BEGIN {WORK}

COMMIT {WORK} {AND {NO} CHAIN} {{NO} RELEASE}

ROLLBACK {WORK} {AND {NO} CHAIN} {{NO} RELEASE}

SET autocommit = (1, 0);

Here:

  • MariaDB START TRANSACTION, where the synonym of the keyword can be the BEGIN or the BEGIN WORK.
  • COMMIT command to save the current MariaDB transaction and make the changes permanent.
  • ROLLBACK command to rollback the current transaction and undo its changes.
  • SET autocommit to activate or deactivate the mode of auto-commit for the current transaction.
  • By default, MariaDB server automatically commits changes to the database and permanently.
  • The parser interprets the BEGIN [WORK] command as the initial part of the BEGIN – END code block in the whole stored programs like stored procedures, functions, and triggers.
  • WORK is optional and it supports ROLLBACK and COMMIT methods.
  • RELEASE & CHAIN provides more control on the transaction’s completion.

Example illustrating the working of START TRANSACTION statement.

Here, we are using two tables i.e. US_City & Cities.

MariaDB US_City Table
MariaDB US_City Table
MariaDB Cities Table
MariaDB Cities Table
START TRANSACTION;
SELECT @X:= Country FROM US_City WHERE ID = 1;
COMMIT;

Here, we are storing country_name in the cities table to a variable i.e. @X where city_id = 1, and storing it into Country in the US_City table from the same variable i.e. @X where ID = 3.

As a result, the NULL value present in US_City changes to US i.e. United States.

MariaDB START TRANSACTION Statement
MariaDB START TRANSACTION Statement

COMMIT – COMMIT saves any data changes made during a transaction so they are visible to subsequent transactions.

The syntax of the COMMIT statement is given below.

COMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]

Here:

  • COMMIT [WORK] – The basic form of Commit statement is simply the keyword COMMIT and the keyword WORK is simple noise which can be ommitted without any changes.
  • AND CHAIN – It is used to initiate a new transaction as soon as the old transaction terminates.
  • RELEASE – It tells the server to disconnect to the server immediately after the current transaction gets terminated.

Example illustrating the working of COMMIT statement.

Here, we are using two tables i.e. US_City & Cities.

MariaDB US_City Table
MariaDB US_City Table
MariaDB Cities Table
MariaDB Cities Table
START TRANSACTION;
SELECT @X:= Country FROM US_City WHERE ID = 1;
UPDATE cities SET country_name = @X WHERE city_id > 0;
COMMIT;

Here, we are storing Country in the US_City table to a variable i.e. @X where ID = 1, and storing it into country_name in the cities table from the same variable i.e. @X where city_id > 0.

As a result, the value present in cities changes from US i.e. United States to USA i.e. United States Of America.

MariaDB Cities Table
MariaDB Cities Table

ROLLBACK – Rollback is the process of undoing transactions that have not been saved in the database. It can only undo the changes since the last commit.

The syntax of the Rollback Statement in MariaDB is given below.

ROLLBACK;

It is mostly used after a set of statements leading to changes in the data since the last commit.

Example illustrating the working of ROLLBACK statement in MariaDB.

The table used i.e. cities before any changes are shown below.

MariaDB Cities Table
MariaDB Cities Table
START TRANSACTION;
INSERT INTO cities(cname, state_name, country_name)
    -> SELECT City, State, Country FROM US_City;

Here, we are inserting the data of US_City into the cities table using the INSERT INTO SELECT statement in MariaDB.

After running the INSERT INTO SELECT on the cities table in MariaDB.

MariaDB Transaction
MariaDB Transaction

Here, we can see that the records of the USA_City table have been added to the cities table.

Now, we will run ROLLBACK STATEMENT to see what happens.

ROLLBACK;
MariaDB ROLLBACK
MariaDB ROLLBACK Statement

Here, you can see that the records of the US_City table are not present in the cities table.

Also, take a look at some more MariaDB tutorials.

In this tutorial, we have learned about MariaDB Transaction. Additionally, we have covered the following topics.

  • MariaDB Transaction
  • MariaDB Transaction Rollback Example
  • MariaDB Transaction Log
  • MariaDB Transaction Isolation Level
  • MariaDB Transaction Timeout
  • MariaDB Transaction Rollback On Error
  • MariaDB Transactional DDL
  • MariaDB Transaction Example
  • MariaDB Transaction Alter Table
  • MariaDB Statements That Cause An Implicit Commit
  • MariaDB Transaction Autocommit
  • MariaDB Kill Transaction
  • MariaDB Transaction Query