0% found this document useful (0 votes)
12 views

SQL Transaction Commit, Autocommit & Rollback.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

SQL Transaction Commit, Autocommit & Rollback.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Mastering SQL Transactions: COMMIT, AUTOCOMMIT, and ROLLBACK

What is a Transaction?

A transaction in SQL is a sequence of operations performed as a single logical unit of work.

It ensures that either all the operations succeed (commit) or none take effect (rollback).

Think of it as an "all-or-nothing" approach!

COMMIT: Confirm Changes

The COMMIT command saves all the changes made during the current transaction permanently.

Example:

START TRANSACTION;

UPDATE Employee SET Salary = Salary + 5000 WHERE Department = 'IT';

COMMIT; -- Changes are saved

Key Points:

- Once a COMMIT is executed, changes are permanent and visible to other users.

- Useful for operations like payroll updates or inventory adjustments.

AUTOCOMMIT: Automatic Save Mode

Some databases (like MySQL) operate in AUTOCOMMIT mode by default, meaning every SQL

statement is treated as

a transaction and is committed automatically.

Page 1
Example:

-- AUTOCOMMIT mode (default in MySQL)

UPDATE Employee SET Salary = Salary + 5000 WHERE Department = 'HR';

-- Changes are auto-saved.

Key Points:

- Great for small, independent queries.

- To disable AUTOCOMMIT: SET autocommit = 0;

ROLLBACK: Undo Changes

The ROLLBACK command undoes changes made in the current transaction if something goes

wrong.

Example:

START TRANSACTION;

UPDATE Employee SET Salary = Salary + 5000 WHERE Department = 'Finance';

ROLLBACK; -- Undo changes

Key Points:

- Ideal for error recovery to avoid corrupting data.

- Only works if changes are not committed yet.

Best Practices with Transactions

Page 2
1. Use transactions when performing multiple related operations to ensure consistency.

2. Turn off AUTOCOMMIT for workflows requiring manual control.

3. Always test queries before committing, especially in production.

4. For databases in AUTOCOMMIT mode, explicitly use START TRANSACTION for grouped

operations.

Page 3

You might also like