SQL Transactions Examples
Quick Answer
SQL transactions group multiple database operations into a single unit that either fully succeeds or fails, ensuring data integrity. Examples include using BEGIN TRANSACTION, COMMIT to save changes, ROLLBACK to undo, and SAVEPOINT to partially revert within a transaction.
Learning Objectives
- Understand how to start and end SQL transactions.
- Learn how to use COMMIT and ROLLBACK commands.
- Explore SAVEPOINT usage for partial rollbacks within transactions.
Introduction
SQL transactions are essential for maintaining data integrity during multiple related database operations.
This tutorial provides practical examples to help you understand how to use transactions effectively.
A transaction is a unit of work that is either fully completed or fully failed.
Basic Transaction Example
A basic transaction groups multiple SQL statements so they execute as a single unit.
If all statements succeed, the transaction is committed; otherwise, it is rolled back.
- Start with BEGIN TRANSACTION or START TRANSACTION.
- Execute your SQL statements.
- Use COMMIT to save changes or ROLLBACK to undo.
Example: Transferring Funds Between Accounts
This example demonstrates transferring money from one bank account to another using a transaction.
Using SAVEPOINT for Partial Rollbacks
SAVEPOINT allows you to set a point within a transaction to which you can rollback without aborting the entire transaction.
This is useful for complex transactions where some operations can be undone without losing all progress.
- Create a savepoint with SAVEPOINT savepoint_name.
- Rollback to a savepoint with ROLLBACK TO savepoint_name.
- Continue the transaction or commit after partial rollback.
Practical Example
This transaction deducts $100 from account 1 and adds it to account 2. If both updates succeed, changes are saved with COMMIT.
If an error occurs during the transaction, ROLLBACK undoes all changes made so far.
This example rolls back only the second update, preserving the first, then commits the transaction.
Examples
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;This transaction deducts $100 from account 1 and adds it to account 2. If both updates succeed, changes are saved with COMMIT.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- Suppose an error occurs here
ROLLBACK;If an error occurs during the transaction, ROLLBACK undoes all changes made so far.
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
SAVEPOINT deduct_done;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
-- Error detected, rollback to savepoint
ROLLBACK TO deduct_done;
COMMIT;This example rolls back only the second update, preserving the first, then commits the transaction.
Best Practices
- Always use transactions when performing multiple related database operations.
- Use COMMIT only after all operations succeed to ensure data consistency.
- Use ROLLBACK to handle errors and maintain database integrity.
- Leverage SAVEPOINTS for complex transactions requiring partial rollbacks.
- Keep transactions as short as possible to reduce locking and improve performance.
Common Mistakes
- Forgetting to commit a transaction, leaving changes uncommitted.
- Not using transactions for multiple related operations, risking partial updates.
- Using long transactions that lock resources unnecessarily.
- Ignoring error handling inside transactions.
- Misusing SAVEPOINTS without proper rollback logic.
Hands-on Exercise
Create a Transaction with Savepoint
Write a SQL transaction that updates two tables. Use a savepoint after the first update and rollback to it if the second update fails.
Expected output: A transaction that partially rolls back on failure and commits successful changes.
Hint: Use BEGIN TRANSACTION, SAVEPOINT, ROLLBACK TO, and COMMIT commands.
Simulate a Failed Transaction
Write a transaction that attempts to insert data into a table but rolls back if a constraint violation occurs.
Expected output: No changes are saved if the insert fails.
Hint: Use error handling with ROLLBACK.
Interview Questions
What is the purpose of a SQL transaction?
InterviewA SQL transaction ensures that a group of database operations execute as a single unit, maintaining data integrity by either committing all changes or rolling back all if any operation fails.
How does ROLLBACK differ from COMMIT in SQL transactions?
InterviewCOMMIT saves all changes made during the transaction permanently, while ROLLBACK undoes all changes made during the transaction.
When would you use a SAVEPOINT in a transaction?
InterviewSAVEPOINT is used to set intermediate points within a transaction to which you can rollback partially without aborting the entire transaction.
MCQ Quiz
1. What is the best first step when learning Examples?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Examples?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. SQL transactions group multiple database operations into a single unit that either fully succeeds or fails, ensuring data integrity.
B. Examples never needs examples
C. Examples is unrelated to practical work
D. Examples should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Transactions ensure atomicity and consistency in database operations.
- COMMIT saves all changes made in a transaction permanently.
- ROLLBACK undoes all changes made in the current transaction.
- SAVEPOINT allows partial rollback to a specific point within a transaction.
- SQL transactions group multiple database operations into a single unit that either fully succeeds or fails, ensuring data integrity.
Summary
SQL transactions are vital for ensuring data consistency and integrity during multiple related operations.
Using COMMIT and ROLLBACK controls whether changes are saved or undone.
SAVEPOINTS provide flexibility for partial rollbacks within complex transactions.
Frequently Asked Questions
What is a SQL transaction?
A SQL transaction is a sequence of operations performed as a single logical unit of work, which either fully completes or fully fails.
Why use transactions in SQL?
Transactions ensure data integrity by making sure that related operations either all succeed or all fail together.
Can I rollback only part of a transaction?
Yes, using SAVEPOINTS you can rollback to a specific point within a transaction without undoing the entire transaction.





