Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should there be a Transaction for Read Queries?

I've been reading that some devs/dbas recommend using transactions in all database calls, even read-only calls. While I understand inserting/updating within a transaction what is the benefit of reading within a transaction?

like image 927
Kyle West Avatar asked Nov 21 '08 14:11

Kyle West


People also ask

Does query need to be in transaction?

The "Q" in SQL stands for "Query": All SQL is a "query" even if it doesn't return anything (eg a create table query) - search for DDL, DML and DCL). All queries are run within a transaction.

When should transaction be used?

You use transactions when you have a group of actions that must be atomic (either all succeed or none succeed) Wrapping these actions in a transaction allows you to rollback actions that have already succeeded when you encounter an error.

Is reading from database a transaction?

The answer is that you don't. Starting a transaction to perform a read-only operation adds to the overhead of the processing thread and can cause shared read locks on the database (depending on what type of database you are using and what the isolation level is set to).

When should I use transaction in SQL?

You use transactions when the set of database operations you are making needs to be atomic. That is - they all need to succeed or fail. Nothing in between. Transactions are to be used to ensure that the database is always in a consistent state.


2 Answers

So you get a consistent view of the database. Imagine you have two tables that link to each other, but for some reason you do 2 selects... in pseuodocode:

myRows = query(SELECT * FROM A) moreRows = query(SELECT * FROM B WHERE a_id IN myRows[id]) 

If between the two queries, someone changes B to delete some rows, you're going to have a problem.

like image 164
Greg Avatar answered Sep 22 '22 08:09

Greg


Similar to what RoBorg said, you'd do SELECTS w/i transactions to prevent the reading of phantom data between statements. BUT it's important to note that the default transaction isolation level in SQL Server is READ COMMITTED which will only prevents dirty reads; to prevent phantom data you'd have to use at least REPEATABLE READ. "Use this option only when necessary."

http://msdn.microsoft.com/en-us/library/ms173763.aspx

like image 37
Booji Boy Avatar answered Sep 22 '22 08:09

Booji Boy