Cristian Vrabie
Cristian Vrabie

Reputation: 4068

Dirty read or phantom read in multiple insert transaction?

I understand the examples given for "dirty reads" and "phantom reads" on the wikipedia page for isolation levels. However I'm not sure how to categorise the following situation and what isolation level or different strategy to apply in order to avoid this situation.

  1. Transaction 1: Inserts row in table A
  2. Transaction 2: Selects row in table A
  3. Transaction 2: Selects row in table B based on something in the previous read
  4. Transaction 2: Commit
  5. Transaction 1: Inserts row in table B
  6. Transaction 1: Commit

The problem is that Transaction 2 selects something in B before T1 finished writing in both tables. The select in step 3 might need to select the row inserted in 5 to be correct. Is this a dirty read, phantom read or neither. Would a READ_COMMITTED isolation level be enough to avoid problems? As I understand it, with READ_COMMITTED T2 should not read the new row inserted by T1 at that point.

Upvotes: 3

Views: 2329

Answers (1)

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

This is a dirty read. In READ_COMMITTED isolation level the query in step 2 will not return the row you have inserted in step 1 but haven't committed yet, thus preventing the unsuccessful attempt to access data that hasn't been inserted yet.

A phantom read would mean that you are executing the same query twice inside Transaction 2 and getting a different set of results.

Upvotes: 1

Related Questions