cancel
Showing results for 
Search instead for 
Did you mean: 

How to prevent another transaction from inserting the row I'm about to insert?

VolkerBarth
Contributor
7,502

Based on this FAQ, I would like to ask how I can prevent another transaction to insert a row in a table with a PK value I'm about to insert?

To use the sample from the other question, say I have this table:

CREATE TABLE MyTermTable ( 
   MyTerm INTEGER NOT NULL PRIMARY KEY,
   counter INTEGER NOT NULL );

And I have a particular value for PK column MyTerm to insert (say, as @MyTerm).

How can I prevent others to insert that value?

Current solutions (from the cited FAQ) include:

  • Just try to insert that row and handle according PK conflicts accordingly.

  • Do a blocking select (with requires isolation level 3) and insert the row. PK violations aren't possible. Disadvantage: This may prevent insertions of any different @MyTerm value as well, and deadlocks need to be handled.
    (Note: The amount of blocking will depend on what kind of table/index scan is used to build the select's result set. As I understand, when the query optimizer uses an index (e.g. for the MyTerm PK), lesser rows will be blocked.)

Are there other solutions that allow "my insert" to succeed and allow other transactions to get as much work done as possible?

Note: This is primarily a question to get a better understanding how to solve such generic problems.

Accepted Solutions (0)

Answers (1)

Answers (1)

MCMartin
Participant

What about the Lock Table Statement? You have control independent of the current isolation level.

VolkerBarth
Contributor
0 Kudos

Sure, but that would also prevent any modification on that table - including all updates and deletes of existing rows...

MCMartin
Participant
0 Kudos

So performance is the key of your question.

VolkerBarth
Contributor
0 Kudos

Sorry, that I haven't stated the focus (I'm gonna edit the question) - it's more or less a question to gain a better understanding.