QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Changing data and transactions

What is a SAVEPOINT and how does it help with test data?

SAVEPOINT sets a named mark inside a transaction, and ROLLBACK TO SAVEPOINT undoes only the commands after it. In PostgreSQL this revives an aborted transaction after an expected error, so a negative case does not destroy the rest of the prepared data. The mark stays after the rollback, and id sequences are not rolled back. Outside a transaction SAVEPOINT does not work.

SQL · Changing data and transactions

One negative case in a transaction broke every following command. How do you undo only that one?

A data-setup script works in one transaction. The third insert violated the email uniqueness, and PostgreSQL rejects every following command: the transaction is aborted. Rolling everything back loses the first two inserts. A SAVEPOINT lets you undo only the failed step and continue. This lesson is about how it works and where exactly it helps with test data.

How it works and why. SAVEPOINT name sets a named mark inside an open transaction (it cannot be created outside BEGIN). ROLLBACK TO SAVEPOINT name undoes everything run after the mark, and the transaction is usable again, even if it was aborted before. The mark itself stays, so you can roll back to it once more, while marks created later disappear. RELEASE SAVEPOINT name removes the mark and keeps the changes after it. The reason: a partial undo is needed so that one expected error does not force a rollback of the whole long scenario.

Example: a duplicate email and the transaction lives on.

CREATE TABLE usr (id serial PRIMARY KEY, email text UNIQUE);

BEGIN;
INSERT INTO usr (email) VALUES ('a@test.io');
SAVEPOINT sp;
INSERT INTO usr (email) VALUES ('a@test.io');
-- ERROR: duplicate key value violates unique constraint "usr_email_key"
SELECT 1;
-- ERROR: current transaction is aborted, commands ignored
--        until end of transaction block
ROLLBACK TO SAVEPOINT sp;
INSERT INTO usr (email) VALUES ('b@test.io');
COMMIT;

SELECT id, email FROM usr ORDER BY id;
-- (1, a@test.io), (3, b@test.io)

The first row stayed, the duplicate was rolled back, and the other insert ran after ROLLBACK TO. The ids in the result are 1 and 3: the failed insert used 2, and a sequence is not rolled back.

Reading the errors: cause and effect

INSERT INTO usr (email) VALUES ('a@test.io');
1ERROR:  duplicate key value violates unique constraint "usr_email_key"
2DETAIL:  Key (email)=(a@test.io) already exists.
SELECT 1;
3ERROR:  current transaction is aborted, commands ignored until end of transaction block
  1. Cause: UNIQUE rejected the second insert. This is the only real failure.
  2. Value: DETAIL shows which key already exists. It makes clear the test inserted a duplicate and did not break the database.
  3. Effect: even an innocent SELECT 1 after the error gets this answer until the transaction is rolled back or returned to a mark.

What to do

ROLLBACK TO SAVEPOINT sp undoes only the failed insert and brings the transaction back to work.

Figure 1. The real PostgreSQL messages from the example (shortened): the numbers lead to the explanations.

Where it helps with test data.

  • Negative cases at the database level: checking that CHECK, UNIQUE or FOREIGN KEY rejects a bad row. A SAVEPOINT is set before each attempt, and after the expected error you roll back to it and continue in the same transaction.
  • A setup script where one step may fail while the rest of the data is still needed: the step is wrapped in a SAVEPOINT.
  • A test inside an outer transaction that is rolled back at the end: the nested "transactions" of test helpers are usually savepoints, so an inner rollback does not destroy the outer context.

Limits and alternatives. A mark exists only inside a transaction and disappears when it ends. A rollback does not return sequences. For "insert if missing" INSERT ... ON CONFLICT DO NOTHING is often simpler, since it raises no error at all. Wrapping a test in a transaction (savepoints included) does not help when the test and the application use different connections: the application cannot see the test's uncommitted data, so the data is committed and cleaned up explicitly. SAVEPOINT, ROLLBACK TO SAVEPOINT and RELEASE SAVEPOINT also exist in MySQL (InnoDB).

Common mistakes.

  • Writing on after an error without ROLLBACK TO: in PostgreSQL every command is rejected until the transaction ends.
  • Setting the mark after the error: you can roll back only to a mark created before it.
  • Expecting ROLLBACK TO to return the id counter or to end the transaction: it only undoes the commands after the mark.
  • Forgetting COMMIT after rolling back to a mark: the transaction stays open and holds locks.

Check yourself

The second command in a transaction failed, and a SAVEPOINT sp was set before it. Which command restores work and what is kept?

Answer

ROLLBACK TO SAVEPOINT sp. Everything before the mark is kept, the commands after it are undone, and the transaction works again.

After ROLLBACK TO SAVEPOINT sp, does the mark sp still exist?

Answer

Yes. Only marks created after it disappear, so you can roll back to sp again.

In an interview. Junior: SAVEPOINT sets a mark in a transaction, and ROLLBACK TO undoes only the changes after it, not the whole transaction. Middle/Senior: In PostgreSQL it is the way to survive an expected error in an aborted transaction. I use it for negative cases in data setup, I remember that sequences are not rolled back, and where possible I use ON CONFLICT.

More articles in this chapter