What is the difference between non-repeatable read and phantom read?
I have read the Isolation (database systems) article from Wikipedia, but I have a few doubts. In the below example, what will happen: the non-repeatable read and phantom read?
####Transaction A
SELECT ID, USERNAME, accountno, amount FROM USERS WHERE ID=1
####OUTPUT:
1----MIKE------29019892---------5000
####Transaction B
UPDATE USERS SET amount=amount+5000 where ID=1 AND accountno=29019892;
COMMIT;
####Transaction A
SELECT ID, USERNAME, accountno, amount FROM USERS WHERE ID=1
Another doubt is, in the above example, which isolation level should be used? And why?
From Wikipedia (which has great and detailed examples for this):
A non-repeatable read occurs, when during the course of a transaction, a row is retrieved twice and the values within the row differ between reads.
and
A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.
Simple examples:
select sum(x) from table;
will return a different result even if none of the affected rows themselves have been updated, if rows have been added or deleted.In the above example,which isolation level to be used?
What isolation level you need depends on your application. There is a high cost to a "better" isolation level (such as reduced concurrency).
In your example, you won't have a phantom read, because you select only from a single row (identified by primary key). You can have non-repeatable reads, so if that is a problem, you may want to have an isolation level that prevents that. In Oracle, transaction A could also issue a SELECT FOR UPDATE, then transaction B cannot change the row until A is done.