woowacourse-study / 2022-Real-MySQL

⚡️토르⚡️의 짜릿한 Real MySQL 뽀개기 🔨
9 stars 3 forks source link

Non-Repeatable Read VS Phantom Read #8

Open awesomeo184 opened 2 years ago

awesomeo184 commented 2 years ago

주제

non-repeatable read와 phantom read의 차이에 대하여

선정 이유

둘 다 한 트랜잭션 내에서 조회 쿼리를 두 번 실행했을 때 결과가 다른 것인데, 어떤 차이가 있어서 다른 이름으로 부르는지 이해가 되지 않아서 차이점을 정리해봤다.

해당 텍스트

한 트랜잭션 내에서 같은 쿼리를 두 번 실행했을 때...

즉 non-repeatable read는 "한 레코드의 값"에 초점이 맞춰져있고, phantom read는 "레코드의 존재 유무"에 초점이 맞춰져 있는 것이다.

Non-Repeatable Read의 경우 트랜잭션 ID를 부여해 자신의 버전보다 낮은 버전의 데이터만 읽는 Repeatable Read 격리수준에서는 발생하지 않는다. 다른 트랜잭션이 수정사항을 커밋하더라도 그 트랜잭션이 자신보다 늦게 생긴 트랜잭션이면 해당 변경사항을 반영하지 않기 때문이다.

phantom read는 일반적으로 Repeatable Read 이하의 격리수준에서 발생할 수 있다. 그러나 MySQL의 InnoDB의 경우 갭 락과 넥스트 키 락 덕분에 repeatable read에서도 phantom read가 발생하지 않는다(잠금을 동반한 SELECT에서는 발생한다).

관련 페이지

P.180 ~ 183

injoon2019 commented 2 years ago

https://www.youtube.com/watch?v=e9PC0sroCzc&t=27s 07:47

여기서는 Phantom Read가 또 Non-Repeatable 한 종류라고 하네요. 이거 한번 얘기 나눠보시죠

awesomeo184 commented 2 years ago

This can occur when range locks are not acquired on performing a SELECT … WHERE operation. The phantom reads anomaly is a special case of Non-repeatable reads when Transaction 1 repeats a ranged SELECT … WHERE query and, between both operations, Transaction 2 creates (i.e. INSERT) new rows (in the target table) which fulfill that WHERE clause.

https://en.wikipedia.org/wiki/Isolation_(database_systems)#Phantom_reads

위키에서도 phantom read는 non-repeatable read의 special case라고 나오네요.

non-repeatable read는 한 트랜잭션 내에서 select를 두 번 했을 때, 다른 결과가 나오는 경우를 통칭하는 걸로 이해하는게 맞을 것 같습니다.

awesomeo184 commented 2 years ago

https://stackoverflow.com/questions/11043712/what-is-the-difference-between-non-repeatable-read-and-phantom-read

정확히 어느 댓글인지는 못찾겠는데, 여기서는 또 Phantom read는 일어났지만 Non-repeatable Read는 일어나지 않는 상황에 대해서도 언급하고 있네요. 사람마다 생각하는 정의가 다 차이가 있네요;