Learn SQL/Advanced/Transactions/SQL ROLLBACK TO SAVEPOINT

SQL ROLLBACK TO SAVEPOINT

SQL ROLLBACK TO SAVEPOINT helps analysts discard changes after a named savepoint while keeping earlier transaction work pending.

What & Why

The ROLLBACK TO SAVEPOINT pattern is used to discard changes after a named savepoint while keeping earlier transaction work pending. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Marketing wants to validate qualified leads at a savepoint before keeping or discarding only the later work.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
EXAMPLE QUERY
-- SAVEPOINT lead_checkpoint; marks the partial rollback boundary.
-- ROLLBACK TO SAVEPOINT lead_checkpoint; discards only later work.
SELECT
  id AS lead_id,
  email,
  qualified_at,
  converted_at
FROM marketing.leads
WHERE qualified_at IS NOT NULL
ORDER BY lead_id;
RESULT — qualified leads
lead_idemailqualified_atconverted_at
301ana@example.com2024-01-22 11:00:00+002024-02-02 10:00:00+00
303chloe@example.com2024-02-18 14:20:00+00NULL
304dev@example.com2024-03-21 09:00:00+002024-04-04 16:00:00+00

The practice result is read-only while the lesson explains partial rollback behavior.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario