Transactions — Complete Guide
Transactions — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of SQL Server Tutorial on Toolliyo Academy.
On this page
SQL Server Tutorial · Lesson 51 of 100
Transactions
SQL basics ✓ → Queries → Advanced
Queries · 2 — JOINs · ~6 min · SQL — Transactions & Concurrency
What is this?
A transaction groups statements so they all commit or all roll back. BEGIN TRAN / COMMIT / ROLLBACK control that boundary.
Why should you care?
Creating an order and deducting stock must not leave half-done work if the second step fails.
See it live — copy this example
Run in SQL Server Management Studio (SSMS) or Azure Data Studio.
USE DataVerse;
BEGIN TRY
BEGIN TRAN;
UPDATE dbo.Accounts SET Balance = Balance - 100 WHERE AccountId = 1;
UPDATE dbo.Accounts SET Balance = Balance + 100 WHERE AccountId = 2;
COMMIT;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
What happened?
- Both balance updates succeed together or neither keeps changes.
- CATCH rolls back if anything throws mid-way.
Practice next
- Seed two Accounts with known balances.
- Run the transfer transaction.
- Force an error after the first UPDATE and confirm rollback.
- Add an INSERT into a TransferAudit table inside the tran.
- Nest a savepoint (covered later concepts).
Remember
Transactions make multi-step changes atomic. COMMIT finishes; ROLLBACK undoes. Always handle errors with rollback.
Checkout must be atomic
DataVerse checkout writes order + decreases stock in one tran.
Outcome: No order without stock movement, and the reverse.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!