Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use transactions for select statements?

I don't use Stored procedures very often and was wondering if it made sense to wrap my select queries in a transaction.

My procedure has three simple select queries, two of which use the returned value of the first.

like image 328
chobo Avatar asked May 12 '11 18:05

chobo


People also ask

Does SELECT statement need a transaction?

If a statement completes successfully, it is committed; if it encounters any error, it is rolled back. Even selects or DDL statements have their own implicit transaction and so they have autocommit to. But usually a select has nothing to commit.

Can we use transaction in SQL function?

1 Answer. Show activity on this post. That's why transactions are unnecessary for sql-server functions. However, you can change transaction isolation level, for example, you may use NOLOCK hint to reach "read uncommitted" transaction isolation level and read uncommitted data from other transactions.

Why do we use transactions 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.

When should transaction be used?

The following are some frequent scenarios where use of transactions is recommended: In batch processing, where multiple rows must be inserted, updated, or deleted as a single unit. Whenever a change to one table requires that other tables be kept consistent. When modifying data in two or more databases concurrently.


2 Answers

In a highly concurrent application it could (theoretically) happen that data you've read in the first select is modified before the other selects are executed.

If that is a situation that could occur in your application you should use a transaction to wrap your selects. Make sure you pick the correct isolation level though, not all transaction types guarantee consistent reads.

Update : You may also find this article on concurrent update/insert solutions (aka upsert) interesting. It puts several common methods of upsert to the test to see what method actually guarantees data is not modified between a select and the next statement. The results are, well, shocking I'd say.

like image 192
Marnix van Valen Avatar answered Oct 01 '22 21:10

Marnix van Valen


Transactions are usually used when you have CREATE, UPDATE or DELETE statements and you want to have the atomic behavior, that is, Either commit everything or commit nothing.

However, you could use a transaction for READ select statements to:
Make sure nobody else could update the table of interest while the bunch of your select query is executing.

Have a look at this msdn post.

like image 22
FIre Panda Avatar answered Sep 30 '22 21:09

FIre Panda