Skip to content
Advertisement

Are changes made to DB only through transactions?

I am not able to get a clear complete understanding regarding the role of transactions in databases.

I know operations clubbed in a transactions will be executed together and then either committed or rolled back.

But then what about about any other query that I write to the database without manually creating a transaction.
Is a transaction created internally for them?

Also what about select statements then? Are transactions created for them too?

I have been using database and sql for some time now, alas I am not clear on these

Advertisement

Answer

Are changes to DBs happening only through transactions? Short answer is yes.

There is always a transaction involved:

  • It might be automatically started (before) and commited (after) every single DML statement you issue, if you’re relying on AUTOCOMMIT behaviour of your database session
  • Or you may explictly start one with BEGIN, execute your statements and end it with COMMIT

I like to think a transaction as a boundary that imposes clear semantics of ATOMICITY and ISOLATION to the statements that are contained within.

You describe atomicity (all or nothing behaviour) but that is not the only guarantee that a transaction can give you: there’s also isolation (and this has to do with reads you within transactions (E.g. SELECTs).

In a concurrent application (many clients writing and reading to the same db/table at the same time), transaction ISOLATION is the property that defines “how much of the effects of other operations” can be observed in the current one. For example, assume you need to perform a transaction that involves doing the same SELECT multiple times: do you want this SELECT to return (possibly) different results each time (because some modification happened concurrently) or not?

For single statements is:

  • A single DML (UPDATE, INSERT…) statement by itself is effectively “As if it was in a transaction with a single statement, that gets immediately commited after execution” (Either it works like this because you’re in AUTOCOMMIT, or you wrapped a single statement within BEGIN…COMMIT)

  • For a single SELECT it’s the same. The transaction in this case (implicit or not, gives you the possibility of specifiying different isolation levels). It might sound strange to consider transactions for SELECTS, but requiring particular isolation levels might mean that the db is acquiring some lock to the data under the hood: committing the transaction in that case would release such lock.

Since you tagged mysql, here you can read on transaction isolations supported by mysql:
https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement