From the course: Database Foundations: Database Management

Transactions and data consistency

From the course: Database Foundations: Database Management

Start my 1-month free trial

Transactions and data consistency

- [Instructor] When modifying data that's stored in your tables, it's often the case that certain changes will have to be made at the same time in order to keep values in a consistent state across your data tables. For instance, when a customer places a product into their online shopping cart, you need to add the item to their cart and simultaneously remove the item from your inventory. If you don't do both steps at exactly the same moment, it could be possible for two different customers to put the same item in their carts at the same time, and that would cause you to oversell the item and potentially upset one of your customers when you're unable to fulfill their order. We need a way to ensure that multiple changes to the database happen at the same time. The way that we do that is by combining several commands together in a single operation called a transaction. Transactions create a single unit of work out of many different commands. The nice thing about transactions are that the entire batch of commands are evaluated together as a whole. If all of the commands inside of the transaction finish successfully, the entire transaction will complete and update the database all at once. On the other hand, if one of the statements inside of the transaction fail for any reason, say the command is interrupted or violates a table constraint or the database becomes unresponsive halfway through. If there's a failure of any command within the transaction at all, the entire transaction fails. This means that any database changes that were successful are undone, a process that's called a rollback. This leaves the database in the same state that it was in before the transaction even began. Wrapping batch of related commands into a single transaction helps ensure that the state of the data remains consistent and trustworthy whenever you're creating new rows, deleting rows, or modifying existing rows in your data tables. That's because the entire batch will either succeed or fail together.

Contents