Question

Say that a method only reads data from a database and does not write to it. Is it always the case that such methods don't need to run within a transaction?

Was it helpful?

Solution

No. If you don't read at a specific isolation level you might not get enough guarantees. For example rows might disappear or new rows might appear.

This is true even for a single statement:

select * from Tab
except select * from Tab

This query can actually return rows in case of concurrent modifications because it scans the table twice.

SQL Server: There is an easy way to get fast, nonblocking, nonlocking, consistent reads: Enable snapshot isolation and read in a snapshot transaction. AFAIK Oracle has this capability as well. Postgres too.

OTHER TIPS

In many databases a request for reading from the database which is not in an explicit transaction implicitly creates a transaction to run the request.

In a SQL database you may want to use a transaction if you are running multiple SELECT statements and you don't want changes from other transactions to show up in one SELECT but not an earlier one. A transaction running at the SERIALIZABLE transaction isolation level will present a consistent view of the data across multiple statements.

the purpose of transaction is to rollback or commit the operations done to a database, if u are just selecting values and making no change in the data there is no need of transaction.

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