🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Transactions (COMMIT, ROLLBACK)

SQL AdvancedTCLđŸŸĸ Free Lesson
SQL Advanced

Transactions (COMMIT, ROLLBACK)

Ensure data consistency with atomic operations that either fully succeed or fully fail.

  • COMMIT — Permanently saves all changes made during the current transaction
  • ROLLBACK — Reverts all changes made during the current transaction to a previous state
  • SAVEPOINT — Creates intermediate checkpoints for partial rollbacks within a transaction Without transactions, partial failures leave your database in an inconsistent state.

What Is a Transaction?

BEGINSQL Ops...OK?COMMITChanges SavedROLLBACKChanges RevertedYesError

Transactions are the foundation of data integrity in relational databases. They guarantee that complex operations — such as transferring money between accounts — either complete entirely or not at all, even in the event of system failures.

-- A classic bank transfer as a single transaction
BEGIN TRANSACTION;

UPDATE accounts SET balance = balance - 500 WHERE account_id = 1001;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2002;

COMMIT;

The ACID Properties

PropertyMeaningExample
AtomicityAll operations in a transaction succeed or none doA transfer debits and credits — or neither happens
ConsistencyA transaction brings the database from one valid state to anotherTotal balance across accounts remains constant
IsolationConcurrent transactions do not interfere with each otherTwo transfers on the same account are serialized
DurabilityOnce committed, changes survive system failuresA committed transfer persists after a power outage

BEGIN, COMMIT, and ROLLBACK

Every transaction starts with BEGIN and ends with either COMMIT (success) or ROLLBACK (failure).

-- Start a transaction
BEGIN TRANSACTION;

-- Perform operations
INSERT INTO orders (customer_id, product_id, quantity, order_date)
VALUES (42, 7, 3, GETDATE());

UPDATE inventory SET stock = stock - 3 WHERE product_id = 7;

-- Verify before committing
SELECT * FROM orders WHERE customer_id = 42;
SELECT * FROM inventory WHERE product_id = 7;

-- If everything looks correct
COMMIT;

-- If something went wrong
-- ROLLBACK;
-- Error handling with transactions
BEGIN TRANSACTION;

BEGIN TRY
    UPDATE accounts SET balance = balance - 1000 WHERE id = 1;
    UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
    INSERT INTO transfer_log (from_id, to_id, amount, transfer_date)
    VALUES (1, 2, 1000, GETDATE());
    COMMIT;
END TRY
BEGIN CATCH
    ROLLBACK;
    THROW;
END CATCH;

SAVEPOINT for Partial Rollbacks

BEGIN TRANSACTION;

INSERT INTO customers (name, email) VALUES ('Alice', '[email protected]');
SAVEPOINT after_customer_insert;

INSERT INTO orders (customer_id, product_id, quantity)
VALUES (SCOPE_IDENTITY(), 5, 2);

-- Oops, wrong product — roll back only the order
ROLLBACK TO SAVEPOINT after_customer_insert;

-- Customer insert is still intact — insert correct order
INSERT INTO orders (customer_id, product_id, quantity)
VALUES (SCOPE_IDENTITY(), 8, 2);

COMMIT;

Transaction Isolation Levels

Different isolation levels balance consistency against concurrency. Higher isolation reduces anomalies but decreases performance.

Isolation LevelDirty ReadNon-Repeatable ReadPhantom ReadPerformance
READ UNCOMMITTEDPossiblePossiblePossibleHighest
READ COMMITTEDPreventedPossiblePossibleHigh
REPEATABLE READPreventedPreventedPossibleMedium
SERIALIZABLEPreventedPreventedPreventedLowest
-- Set isolation level for a session
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;

-- This transaction now runs with full isolation
SELECT * FROM products WHERE category = 'Electronics';
-- No phantom reads allowed — other transactions cannot insert
-- new Electronics rows while this transaction is active

UPDATE products SET price = price * 0.9 WHERE category = 'Electronics';
COMMIT;

-- Or set it per-transaction
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
SELECT * FROM inventory WHERE product_id = 42;
COMMIT;

Autocommit Behavior

Most database clients operate in autocommit mode by default, where each individual statement is implicitly treated as its own transaction.

-- Autocommit (default in most clients)
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- This is committed immediately

-- Explicit transaction gives you control
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- Not yet committed — can still be rolled back
ROLLBACK;
-- The UPDATE is undone

Nested Transactions

SQL Server supports nested BEGIN TRANSACTION calls, but only the outermost COMMIT actually persists changes. Inner commits merely decrement the transaction nesting level.

BEGIN TRANSACTION;          -- nesting level = 1
    INSERT INTO logs (message) VALUES ('Step 1');

    BEGIN TRANSACTION;      -- nesting level = 2
        INSERT INTO logs (message) VALUES ('Step 2');
    COMMIT;                 -- nesting level = 1 (no real commit)

    BEGIN TRANSACTION;      -- nesting level = 2
        INSERT INTO logs (message) VALUES ('Step 3');
    ROLLBACK;               -- undoes Step 3 only, nesting = 1

COMMIT;                     -- commits Step 1 and Step 2

Practical Example: Order Processing

BEGIN TRANSACTION;

-- Step 1: Create the order
INSERT INTO orders (customer_id, order_date, status)
VALUES (101, GETDATE(), 'PENDING');

DECLARE @order_id INT = SCOPE_IDENTITY();

-- Step 2: Add order items
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (@order_id, 10, 2, 29.99),
       (@order_id, 15, 1, 49.99);

-- Step 3: Update inventory
UPDATE inventory SET stock = stock - 2 WHERE product_id = 10;
UPDATE inventory SET stock = stock - 1 WHERE product_id = 15;

-- Step 4: Verify stock is not negative
IF EXISTS (SELECT 1 FROM inventory WHERE stock < 0)
BEGIN
    RAISERROR('Insufficient stock', 16, 1);
    ROLLBACK;
    RETURN;
END

-- Step 5: Update order total
UPDATE orders
SET total = (SELECT SUM(quantity * unit_price) FROM order_items WHERE order_id = @order_id)
WHERE order_id = @order_id;

COMMIT;

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement