SQL Transactions

SQL transactions are used to group multiple SQL statements into a single unit of work. Transactions allow you to execute multiple queries as a single operation, ensuring that either all of the queries are completed successfully, or none of them are completed at all. This is known as "atomicity" and is an important concept in SQL.

Transactions are useful in a variety of situations, such as when you want to update multiple tables at the same time, or when you want to roll back a set of changes if an error occurs. They are an important part of any SQL query and can help you manage the data in your database more effectively.

Syntax

BEGIN TRANSACTION;
SQL statement 1;
SQL statement 2;
...
COMMIT;
    

Example

BEGIN TRANSACTION;
UPDATE products SET price = price * 1.1 WHERE category = 'clothing';
UPDATE products SET price = price * 1.2 WHERE category = 'shoes';
COMMIT;
    

This example increases the price of all products in the "clothing" category by 10% and the price of all products in the "shoes" category by 20%. The changes are grouped into a single transaction and are either all completed successfully or none of them are completed at all.

You can learn more about SQL transactions and other advanced topics in our SQL tutorials and references.