Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Why transactions?

Tags:

sql

I just realized I've had a headache for years. Well, metaphorically speaking. In reality I was looking at my database structure and somehow just realized I never use transactions. Doh.

There's a lot of data on the internet about transactions (begin transaction, rollback, commit, etc.), but surprisingly not much detail about exactly why they are vital, and just exactly how vital?

I understand the concept of handling if something goes wrong. This made sense when one is doing multiple updates, for example, in multiple tables in one go, but this is bad practice as far as I know and I don't do this. All of my queries just update one table. If a query errors, it cancels, transaction or no transaction. What else could go wrong or potentially corrupt a one table update, besides my pulling the plug out of my server?

In other words, my question is,

exactly how vital is it that i implement transactions on all of my tables - I am fully blasphemous for not having them, or does it really matter that much?

UPDATE

+1 to invisal, who pointed out that queries are automatically wrapped as transactions, which I did not know. Pointed out multiple good references on the subject of my question.

like image 503
dthree Avatar asked Sep 21 '25 10:09

dthree


2 Answers

This made a lot of sense when one is doing multiple updates, for example, in multiple tables in one go. But basically all of my queries just update one table at a time. If a query errors, it cancels, transaction or no transaction.

In your case, it does nothing. A single statement has its own transaction itself. For more information you can read the existed question and answers:

  • What does a transaction around a single statement do?
  • Transaction necessary for single update query?
  • Do i need transaction for joined query?
like image 168
invisal Avatar answered Sep 22 '25 23:09

invisal


Most important property of the database is to keep your data, reliably.

Database reliability is assured by conforming to ACID principles (Atomicity, Consistency, Isolation, Durability). In the context of databases, a single logical operation on the data is called a transaction. Without transactions, such reliability would not be possible.

In addition to reliability, using transactions properly lets you improve performance of some data operations considerably. For example, you can start transaction, insert a lot of data (say 100k rows), and only then commit. Server does not have to actually write to disk until commit is called, effectively batching data in memory. This allows to improve performance a lot.

like image 26
mvp Avatar answered Sep 23 '25 00:09

mvp