is it always necessary to select for a transaction?

Your question doesn’t make much formal sense, as a SELECT can only happen inside a transaction, even if it is only a one-statement-long one.

In your example, your third statement bares no obvious relationship to the first two. What is the overall transaction supposed to accomplish?

Looking just at the first two statements, it looks like you are trying to avoid inserting the same “next” value twice by two concurrent sessions. If both sessions are using serializable isolation level or if you have a unique constraint, then the FOR UPDATE is indeed unnecessary, as serialization failure or unique key violations will prevent that from happening anyway. Of course that does mean you need to catch and retry.

If they are using the default read committed isolation level and with no unique constraint, then FOR UPDATE is also unnecessary, but for an odd reason. The FOR UPDATE is actually not effective at accomplishing the goal, and if your code is going to be wrong it might as well be wrong without a FOR UPDATE.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top