Course contentsShow
← Data Science
Lesson 1113 of 2,14528. Working with Databases from PythonFree lesson

Rolling Back Transactions

Understand how to use rollback to undo all changes in a transaction when errors occur or conditions aren't met.

Rolling Back Transactions

You'll learn how to safely undo database changes when something goes wrong during a transaction.

What Is a Rollback?

A rollback is your "undo" button for database transactions. When you start a transaction (as you learned in the previous lesson), all your changes are held in a temporary state until you commit them. If anything goes wrong—an error occurs, a condition isn't met, or you simply realize the changes shouldn't be saved—a rollback discards all changes made since the transaction began, returning the database to its original state.

Think of it like drafting an email: you can write and revise as much as you want, but until you hit "send" (commit), you can always delete the draft (rollback) and start fresh.

Why Rollbacks Matter

In data science workflows, you often perform multi-step operations: inserting new records, updating calculations, deleting outliers. If step 3 fails, you don't want steps 1 and 2 to remain—your data would be in an inconsistent state. Rolling back ensures all-or-nothing execution.

How to Rollback

When using Python database libraries, you call the rollback() method on your connection object:

conn.rollback()

This reverses every INSERT, UPDATE, or DELETE since the transaction started (or since the last commit).

Typical pattern:

  • Begin transaction (automatic or explicit)
  • Execute queries
  • If everything succeeds: conn.commit()
  • If something fails: conn.rollback()

You typically place rollback in an except block to handle errors gracefully, ensuring your database stays consistent even when things go wrong.

Key Takeaway: Use rollback() to undo all transaction changes when errors occur, maintaining database consistency and data integrity in your Python workflows.