Question presented to candidate: "Walk me through COMMIT, ROLLBACK and SAVEPOINT. What exactly does each one do, and when would you use a savepoint instead of rolling back the whole transaction β for example, importing a batch of customers where a few rows are duplicates?"
What a strong answer should cover:
COMMITmakes every change of the transaction permanent and visible to others;ROLLBACKdiscards all of them and ends the transactionSAVEPOINT namemarks a point inside a transaction;ROLLBACK TO SAVEPOINT nameundoes only the work after it and keeps the transaction (and the savepoint) alive;RELEASE SAVEPOINT nameforgets the mark but keeps the work- Nothing is permanent until the outer
COMMIT: rolling back the outer transaction also discards released savepoints - PostgreSQL aborts the whole transaction after any error ("current transaction is aborted"); a savepoint before the risky statement is how you recover and continue; PL/pgSQL
EXCEPTIONblocks and many ORMs' "nested transactions" are savepoints under the hood - Engine differences: SQLite allows
SAVEPOINToutsideBEGIN(it starts a transaction), PostgreSQL rejects it;COMMITwith no open transaction is an error in SQLite and a warning in PostgreSQL
Code / implementation expected: Yes β a transaction with a savepoint that rolls back one step and commits the rest.
Schema used by the examples: