How to reproduce phantom read in MySQL

How to reproduce phantom read in MySQL

七月 06, 2019

Introduction

In order to deep learn MySQL Transaction Isolation. In this blog, I’ll show how to re-produce phantom read issue.

What I will do

  • Create a table in DB
  • Start 2 MySQL transactions
  • In transaction A, the result of SQL will be affected by transaction B

Environment

Database: MySQL
Engine: is InnoDB
Test table:

1
2
CREATE TABLE t (i INT) ENGINE = InnoDB;
INSERT INTO t (i) VALUES(1);

How to get transactin’s isolation

1
SELECT @@transaction_isolation;

Reproduce phantom read

Session 1 > Set isolation as REPEATABLE READ

set transaction REPEATABLE READ
Select

Session 2 > Insert one line.

Select

Session 1 > Failed to select the line which is inserted in session 2

Select

Session 1 > Try to update the line which is inserted in session 2. expect failure, but it is succussed and we can select it in this transaction.

Select

Summary

Phamtom read will happen in REPEATABLE READ isolcation level.