SQL
Transaction

Working with SQL Transactions

intro

A part of the life of every DBA is to work with transactions in SQL server. Read this article to find out what they are and how to understand SQL transactions.

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

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:

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. Consistency means that your data is always consistent.
  3. Isolation means that some transactions will be isolated (run separately) from other transactions.
  4. Durability means that your data will be okay even if a nightmare scenario occurs (e.g. your power cuts off mid-query,etc.)
  5. Consistency refers to MySQL logging mechanisms;
  6. Isolation refers to InnoDB row-level locking;
  7. 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

How to Deal With a Swollen SQL Transaction Log

author Antonello Zanini tags SQL SQL SERVER 7 min 2025-03-12
title

When, How, and Why to Use the Truncate SQL Statement

author Lukas Vileikis tags DbVisualizer MySQL SQL 6 min 2025-03-11
title

SQL PIVOT: How to Use a Pivot Table In SQL

author Leslie S. Gyamfi tags MySQL POSTGRESQL SQL SQL SERVER 9 min 2025-03-10
title

A Complete Guide to the SQL CREATE INDEX Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 7 min 2025-03-05
title

A Complete Guide to the Order of Execution in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 9 min 2025-03-03
title

SQL Operators: A Complete Walkthrough

author Lukas Vileikis tags DbVisualizer MySQL SQL 4 min 2025-02-25
title

How to Truncate Many Tables In SQL at Once

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-02-24
title

Clustered vs Non-Clustered Index: Complete SQL Guide

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-02-13
title

Queries and Subqueries in SQL: The Definitive Guide

author Lukas Vileikis tags DbVisualizer MySQL POSTGRESQL SQL SQL SERVER 7 min 2025-02-12
title

How to Optimize a Clustered Index Scan in SQL

author Antonello Zanini tags MySQL SQL SQL SERVER 7 min 2025-02-11

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.