기록하는 개발자

PostgreSQL 다중 Update - batch update 본문

DB/PostgreSQL

PostgreSQL 다중 Update - batch update

gitseok 2022. 10. 6. 17:23

300만건이 넘는 데이터를 주기적으로 update 해야하는데 서버와 DB의 과도한 부하 발생을 대비하기 위해 사용

test_table 구조

unnest 는 PostgreSQL의 내장 함수로 입력된 Array를 행집합으로 반환해준다.

 

    update test_table set data = data_table.data
from
(select unnest(array[1, 2, 3, 4]) as id, 
        unnest(array[11, 12, 13, 14]) as data) as ex_data
where test_table.id = ex_data.id;

실행 결과 1

 

 

하지만 id와 data가 별도의 array로 들어가기 때문에 자칫하면 순번이 밀릴수도 있어서 json 형태로 수정

+mybatis foreach 와 접목하기 위해

update test_table
set data = (ex_data->'data')::int
from jsonb_array_elements(
    '[
      { "id": 1, "data": 21 },
      { "id": 2, "data": 22 },
      { "id": 3, "data": 23 },
      { "id": 4, "data": 24 }
    ]') as ex_data
where id = (ex_data->'id')::int

실행 결과 2

정상적으로 수정 완료 

다음 포스팅엔 mybatis foreach를 사용해서 속도 비교까지 진행할 예정

Comments