What is a SAVEPOINT in SQL?
A SAVEPOINT is a way to set a point within a transaction to which you can later roll back if
necessary. It provides more granular control, allowing partial rollback rather than undoing the
entire transaction.
- When to use: When you want to mark certain stages within a transaction and allow
for partial rollback if an error occurs.
Example:
BEGIN TRANSACTION;
SAVEPOINT sp1;
UPDATE employees SET salary = 5000 WHERE id = 1;
- - Something goes wrong
ROLLBACK TO sp1; -- Rolls back to the savepoint, undoing only the
changes after it
COMMIT;