Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transaction necessary for single update query?

I have a mysql query on an InnoDB table like this:

UPDATE items SET qty = qty + 5 WHERE item_id = 1234 LIMIT 1;

Do I need to use a transaction for this? Could anything undesirable happen by not using a transaction?

like image 953
Tony H Avatar asked Jul 25 '13 11:07

Tony H


People also ask

Do we need a transaction for a single query statement?

It does nothing. All individual SQL Statements, (with rare exceptions like Bulk Inserts with No Log, or Truncate Table) are automaticaly "In a Transaction" whether you explicitly say so or not.. (even if they insert, update, or delete millions of rows).

When should transaction be used?

You use transactions when you have a group of actions that must be atomic (either all succeed or none succeed) Wrapping these actions in a transaction allows you to rollback actions that have already succeeded when you encounter an error.

Is every SQL statement a transaction?

A SQL statement always runs in a transaction. If you don't start one explicitly, every SQL statement will run in a transaction of itself. The only choice is whether you bundle multiple statements in one transaction.

Why do we need transaction in database?

The primary benefit of using transactions is data integrity. Many database uses require storing data to multiple tables, or multiple rows to the same table in order to maintain a consistent data set. Using transactions ensures that other connections to the same database see either all the updates or none of them.


1 Answers

Nothing serious can happen. By default, MySQL wraps all single update/insert/delete commands in a transaction. If something goes wrong in the update, then the transaction should be rolled back correctly.

You really only need transactions when you are combining multiple changes and want them all to take effect "at the same time" or "not at all".

You can read more about this in the documentation.

like image 167
Gordon Linoff Avatar answered Sep 30 '22 18:09

Gordon Linoff