SQL
Transaction

Working with SQL Transactions

intro

SQL transactions are a part of the life of every DBA. Every developer has heard of them, too – and they’re not too hard to explain. Look at the query below:

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT
A basic transaction in DbVisualizer
A basic transaction in DbVisualizer

Here’s what’s happening:

  1. BEGIN begins a transaction (we can also use START TRANSACTION to tell our database to initiate the SQL begin transaction process.)
  2. Our SELECT query introduces a variable that’s used inside of itself (“@number.”)
  3. We use the variable to insert data into a table (INSERT INTO query.)
  4. Finally, we COMMIT the operation (save our results.)

That’s a transaction. Not that hard to comprehend!

What is an SQL Transaction?

In simple terms, a transaction in a database world symbolizes “work” that the database needs to perform at once. Think of transactions as units – units that contain work for the database. You start a transaction, define work the database needs to do, then finish it up by committing, or saving, your changes inside of the database.

Transactions can not only be committed (saved) - they can also be rolled back in case an accident occurs. For that, we use the ROLLBACK statement.

Understanding SQL Transactions

Before you start using transactions in your database management system, there are a couple of things you need to know:

  1. Transactions work differently according to your DBMS. Those database management systems that support ACID transactions will make your work easier, while if you’re using those that don’t (non-relational database management systems), you’re risking losing a little of your data.
  2. To understand transactions, it’s helpful to understand ACID - the Atomicity, Consistency, Isolation, and Durability princples:
    1. Atomicity treats changes to a database as a “bundle” of changes.
  3. Consistency means that your data is always consistent.
  4. Isolation means that some transactions will be isolated (run separately) from other transactions.
  5. Durability means that your data will be okay even if a nightmare scenario occurs (e.g. your power cuts off mid-query,etc.)
  6. ACID works differently in different database management systems. As far as MySQL is concerned, it all works like this:
    1. Atomicity means that all statements in a MySQL transaction operate as an indivisible unit and their impacts are either seen collectively or not seen at all;
  7. Consistency refers to MySQL logging mechanisms;
  8. Isolation refers to InnoDB row-level locking;
  9. Durability refers to a log file that tracks all of the changes to the system.

Other database management systems may implement the process a little differently, but the core premise is the same.

  1. Understand race conditions and how they’re prevented in your DBMS. MySQL uses different types of locks to control access to data when a transaction is running. There are shared locks, exclusive locks, intent locks, and row-level locks.
  2. Your database might support different isolation levels (for MySQL, those are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.) Those may need to be accounted for if your transactions are more complex than those given in an example above.

Working with SQL Transactions

Now that you understand SQL transactions from the inside, working with them is a piece of cake. There are only a couple of things you need to keep in mind for your transactions to help your database out:

  1. To avoid using COMMIT after a SQL transaction is finished, set autocommit to 1 or ON. If you don’t do that, you need to issue a COMMIT statement every time you finish a transaction.
  2. Use transactions when you have units of work that are deemed “sensitive” and may need your ability to rollback the changes.
  3. If you use any operations (writes, selects, or inserts) within a transaction within relational databases (such as MySQL server, Percona Server, or MariaDB), keep in mind that they will be performed atomically (all of them will succeed or none of them will succeed.) This is crucial.

SQL transactions should be used whenever there's a possibility of someone else meddling in between you and your data.

Building SQL Transactions

Already have a good understanding of the aforementioned aspects? Perfect, time to build your transaction. Use a trusted SQL client like the one provided by DbVisualizer, and follow these steps – follow them yourself, and later check on our example below:

  1. Deal with commits (autocommit) - turn them on (1/ON) or off (0/OFF.)
  2. Begin a transaction. They say that a good beginning counts as half the work. Especially when you’re bundling work for a transaction to complete. The SQL begin transaction process isn’t as hard as it sounds!
  3. Build your transaction. This is very individual and we can’t give much advice on this – package all of the work here though, and you should be good to go.
  4. End your transaction. This means “save your changes.” Remember the COMMIT operation?

As easy as that!

Our SQL queries should now look like this (“//” and “--” denote comments):

Copy
        
1 autocommit = 0; // disabling automatic commits 2 START TRANSACTION; -- beginning a transaction 3 -- setting variables 4 @demo_variable = 100; 5 @username = 'Jack'; 6 UPDATE accounts SET balance = balance-@demo_variable WHERE username = @username; -- using variables in a transaction. 7 COMMIT;
An example of a transaction in DbVisualizer
An example of a transaction in DbVisualizer

In this transaction, we set two variables, then run an UPDATE statement. Not too complex, but not too shabby either. Keep in mind that the more complex your transactions are, the more time it will take for your database to execute them. You may also need to remove indexes if you’re running UPDATE / DELETE / INSERT queries for your queries to be faster.

Real Life Examples and Caveats of SQL transactions

Transactions are great and we’ve provided an example of how they can be used above. In the real world, things aren’t always as simple as running an UPDATE though – look at this example to start with. Some of the answers within that StackOverflow post illustrate transactions in MySQL well: they are only a thing if we use the InnoDB or XtraDB (the same InnoDB, but with enhanced capabilities) storage engines since they’re the only storage engines that support ACID.

Bear in mind that in some cases, you may also need “checkpoints” to save your progress – your database calls them “savepoints.” A savepoint is basically an identifier of a checkpoint for a transaction and this identifier can be used for rollback operations, release operations, etc. To use a savepoint, use the SAVEPOINT query and after that, name your savepoint. See an example below:

Savepoints in the same SQL query block
Savepoints in the same SQL query block

After you know about savepoints, educate yourself on deadlocks too: a deadlock is basically a “deadly” situation for your database where two or more transactions are waiting for each other to release a resource.

To avoid deadlocks, avoid “Coffman” conditions: these are mutual exclusion, hold-and-wait scenario, circular waiting (waiting for one another), and no preemption possible.

Make sure these conditions are not present in your transactions, save your progress and know your way around ACID – that should help. After you know your way around those, consider using top-rated SQL clients to work with your database: they will help you complete tedious tasks of a DBA with ease. Also, follow our blog – we share a lot of interesting stuff here too!

Summary

In this blog, we’ve walked you through what transactions in your database consist of. Keep in mind that for transactions to be possible, it’s wise to use ACID-compliant database management systems such as MySQL and be aware of the conditions that can make your transactions hell.

Dbvis download link img
About the author
LukasVileikisPhoto
Lukas Vileikis
Lukas Vileikis is an ethical hacker and a frequent conference speaker. He runs one of the biggest & fastest data breach search engines in the world - BreachDirectory.com, frequently speaks at conferences and blogs in multiple places including his blog over at lukasvileikis.com.
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

MySQL 9.0 and the New EXPLAIN Features

author Lukas Vileikis tags MySQL SQL 9 min 2024-11-27
title

Massive SQL DELETE Operations and Database Purging Explained

author Lukas Vileikis tags DELETE SQL 4 min 2024-11-26
title

Postgres Create Array of Numbers: Complete Guide

author Lukas Vileikis tags POSTGRESQL SQL 7 min 2024-11-21
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

A Beginner’s Guide to SQL & Relational Database Management Systems

author Leslie S. Gyamfi tags BEGINNER SQL 5 min 2024-11-19
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

Introducing MariaDB Catalogs: What They Are and How They Work

author Lukas Vileikis tags MIGRATION MySQL SECURITY SQL 5 min 2024-11-13
title

SQL GROUP BY Clause: What It Is, How It Works, How to Approach It

author Lukas Vileikis tags DbVisualizer MySQL SQL 6 min 2024-11-06

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗