[MySQL, MariaDB] auto_increment VS max(id)+1

sua_ahn·2024년 3월 27일
0

MySQL

목록 보기
6/6

운영중인 솔루션 추가 개발 중,
MySQL, MariaDB 시퀀스 컬럼에 auto_increment 설정이 되어있음에도
SELECT문으로 최댓값을 조회하여 INSERT하는 부분 발견!

SELECT MAX(ID) + 1 FROM table;

-- 위에서 조회한 값을 아래 쿼리에서 사용
INSERT INTO table (ID, other columns...)
VALUES (100, ...);

초기 개발 시나 테스트 때 데이터가 안정되지 못하여 사용하던 것이 운영에도 남아있던 것이었다.

auto_increment를 사용하도록 수정하기 전에 다음 사항들을 확인하였다.

  1. 조회한 값을 INSERT할 때 외에 따로 사용하는지 확인했으나, 따로 사용하지 않음
    (솔루션 특성상 해당 코드를 ORACLE 등 다른 DB에도 사용하여 MyBatis의 'useGeneratedKey'기능을 사용하긴 어려움)

  2. 해당 솔루션은 분산DB(다중DB)에는 사용하지 않으므로 auto_increment 사용 가능

  3. Oracle에서는 NEXTVAL을 사용하므로, 삭제로 인한 id값 상승을 막기 위함 아님

  4. EXPLAIN문으로 실행계획을 조회해본 결과, 인덱스 1건만 읽어 성능에 큰 문제를 일으키는 것은 아님

EXPLAIN
SELECT MAX(ID) + 1 FROM table;

Select tables optimized away
Min() 또는 Max()만 SELECT절에 사용되거나, GROUP BY로 MIN(), MAX()를 조회하는 쿼리가 인덱스를 오름차순 또는 내림차순으로 1건만 읽는 최적화가 적용된다면 표시된다.
(특정 인덱스를 1건만 읽으면 되는 경우)

The optimizer determined 1) that at most one row should be returned, and 2) that to produce this row, a deterministic set of rows must be read. When the rows to be read can be read during the optimization phase (for example, by reading index rows), there is no need to read any tables during query execution.

The first condition is fulfilled when the query is implicitly grouped (contains an aggregate function but no GROUP BY clause). The second condition is fulfilled when one row lookup is performed per index used. The number of indexes read determines the number of rows to read.


*참고사이트
https://neunggu.tistory.com/42

profile
해보자구

0개의 댓글