views:

121

answers:

3

Let's say I have 6 records, and I set the fetch size as 2.

[Id] [Name]
 11   A   <-- 1st fetch, start from 1 position
 21   B
 31   C   <-- 2nd fetch, start from 3 position
 41   D
 51   E   <-- 3rd fetch, start from 5 position
 61   F

If 1st user issues a "SELECT * from tablex", and 2nd user issue a "DELETE FROM tablex WHERE Id = 2. The deletion process happen just in time between the 1st fetching and the 2nd fetching.

First fetch (A)

[Id] [Name]
 11   A   <-- 1st fetch, start from 1
 21   B

After deletion from (B)

[Id] [Name]
 11   A   <-- 1st fetch, start from 1
 31   C   
 41   D
 51   E   
 61   F

Now 2nd fetch for (A) should start from 3, but deletion causes position of records have been altered. If the 2nd fetch start with position 3, the records which will be fetched are

[Id] [Name]
 41   D   <-- position 3
 51   E

instead of

[Id] [Name]
 31   C   <-- 2nd fetch, start from 3 position
 41   D

I am not sure if this problem will happen or not. Or the modern db is smart enough to detect it? Or simply lock the table during data retrieving process?

+1  A: 

In MSSQL cannot be such problem, because locking accured while result set retrived. I don't know what about another RDBMS.

Alex_L
Ah yes, Oracle uses row versioning :)
Alex_L
Incorrect: only SERIALIZABLE isolation level provides the level of locking you are speaking about.
AlexKuznetsov
when you read the data (SELECT), records will be locked by Shared (S) lock. Records cannot be edited or deleted until lock released.There will be no lock if you use NOLOCK hint.
Alex_L
Alex_L, there is plenty of evidence proving that you are wrong. Just from the top of my head, this: "The Case of the Skewed Totals"http://www.simple-talk.com/sql/t-sql-programming/the-case-of-the-skewed-totals/
AlexKuznetsov
@both Alexes: any answer here is complicated by the "fetch". Is the select executed as one go, or client side cursor 2 rows at a time?
gbn
@AlexKuznetsov: Ok, I understand that it's not so clear in my head in this topic. @gbn: I considered that janetsmith uses MSSQL cursors, but she (?) says this is ORACLE. In MSSQL, if cursor declared as STATIC or KEYSET, select executed as one go, if DYNAMIC - will be returned by 2 rows at time (or something like).
Alex_L
A: 

What happens will depend, in part, on the isolation levels in force in the two transactions.

If the fetching process is running at serializable isolation, then the DELETE operation will fail. If the fetching process is running at dirty read (read uncommitted) isolation, then almost anything is possible, but most likely, it would read the records that are not deleted.

Jonathan Leffler
+2  A: 

What you ask is called "PHANTOM READ". Most database use locks to prevent this in a transaction.

Some database provide "READ COMMITTED" (or lower) isolation level, phantom read may happens in those case..

J-16 SDiZ