Is it correct to say that data reading operations need not run inside transactions?

StackOverflow https://stackoverflow.com/questions/11186727

  •  16-06-2021
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top