Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use transactions in my queries?

I'm reading very detailed tutorials on how to use transactions with database types and database engines, but I haven't found a guide that teaches me when and why I should use them.

I know transactions are usually used for banking, so when we work with money data, but I can imagine they are used in many other ways.

Today I'm working on a page with various INSERT statements for a relational database, and I wanted to know if this is one of the cases when I should use them.

I get an impression that I don't know the cases when the data can be partially lost (apart from coder errors) so I'm always worried about when I should use them.

Can someone explain or give some link with these fundamental rules?

I'm using MySQL 5.0.8. Should I use InnoDB for all tables that need transactions? If yes, is InnoDB slower than the common MyISAM but I shouldn't worry about that?

thanks

like image 583
vitto Avatar asked Jan 29 '10 00:01

vitto


People also ask

When should I use transaction in SQL?

SQL Transaction gives you the “power to return back to a safe state if some error happens in the middle of your SQL Code”. For example, suppose in your Stored Procedure you are running an Insert statement followed by Update statement.

Should we use transaction for select query?

In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed. If that is a situation that could occur in your application you should use a transaction to wrap your selects.

Why is it important to use transactions in MySQL?

MySQL transaction allows you to execute a set of MySQL operations to ensure that the database never contains the result of partial operations. In a set of operations, if one of them fails, the rollback occurs to restore the database to its original state.


2 Answers

Basically any time you have a unit of work that is either sensitive to outside changes or needs the ability to rollback every change, if an error occurs or some other reason.

Look here for some excellent answers and their reasons for using them.

like image 86
Nick Craver Avatar answered Sep 22 '22 13:09

Nick Craver


In addition to what Nick Craver wrote, you would want to use a transaction when you have a series of writes that need to be performed atomically; that is, they should all succeed or none should succeed.

like image 45
danben Avatar answered Sep 22 '22 13:09

danben