Question

I know that in terms of efficiency it is better to have one big query instead of many small ones, as it is better to reduce the amount of connections with the database to the minimum (especially in context of intense network traffic).

So my question is, besides isolating and atomizing a set of database manipulations (and doing a roll-back if one of them fails) does a transaction act like a big query? I mean, if you need to do many database manipulations, can you wrap it in a transaction and turn it into a single big operation?

Was it helpful?

Solution

No, if I understand what you're asking. You can think of a transaction as setting a checkpoint in the database history so if any of the individual operations within the transaction fails the database state can be restored to the checkpoint. That's a big simplification but conceptually that's how transactions work.

Within a transaction the individual queries are executed separately.

And it's not always better or more efficient to have "one big query instead of many small ones." That depends on what the queries are. It is more efficient to ask for a set of rows in one big query rather than ask for them one at a time. I've actually seen code that does this (pseudocode):

SELECT id FROM people WHERE ... ORDER BY lastname;

for each (id) {
    SELECT firstname, lastname, phone from people WHERE id = {id};
    ...
}

That would be a lot more efficient as

SELECT id, firstname, lastname, phone FROM people WHERE ... ORDER BY lastname;

OTHER TIPS

the problem with this approach is: you will lock some resources and it is bad for concurrency. and if you have one error in one query the rollback will be huge.

I try to avoid transactions and sometimes I need to implement some kind of compensatory transactions if it is possible.

if you need to do many database manipulations, can you wrap it in a transaction and turn it into a single big operation

Yes. That operation will be atomic, just like a single row-update.

In terms of disk I/O: Maybe (depending on how large the transaction is and a multitude of other factors). In terms of network I/O, which you are asking about: No. Transactions are implemented on the server side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top