Question

Given this scenario:

TIME  TRANSACTION 1             TRANSACTION 2
1sec  BEGIN
2sec  INSERT RECORDS INTO T1   
3sec  (doing other things)      BEGIN
4sec  (doing other things)      (doing other things)   
5sec  COMMIT                    (doing other things)   
6sec                            SELECT * FROM T1    <<- GETS ROWS INSERTED BY T1

According to postgres docs:

Also note that two successive SELECT commands can see different data, even though they are within a single transaction, if other transactions commit changes during execution of the first SELECT

The question is: how to avoid SELECT from getting rows committed between the beginning of transaction and the beginning of query.

Was it helpful?

Solution

The situation you describe is called a "phantom read", and is not possible when you use an isolation level that prevents this like REPEATABLE READ or SERIALIZABLE.

http://www.postgresql.org/docs/current/static/transaction-iso.html

You can change the isolation level using the SET TRANSACTION command:

http://www.postgresql.org/docs/current/static/sql-set-transaction.html

Depending on the interface that you use to connect to the database you might also be able to use the corresponding API calls (e.g. Connection.setTransactionIsolation() in Java/JDBC)

OTHER TIPS

Set your transaction isolation level to serializable.

http://www.postgresql.org/docs/9.1/static/transaction-iso.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top