회사 서비스 개발하면서 인덱스 설정은 늘 난제...
근데 이번에 정말로 이상한 일을 겪었다.
완전히 똑같은 type의 크게 다르지 않게 where절 조건을 사용하는데
어느 하나는 단일 인덱스가 걸려서 쿼리가 되고 어느 하나는 되지 않는 굉장히 기이한 현상을 맛보게 되었다...
쿼리는 다음과 같다. (두개를 사용했어야 했다.)
# 1번
explain select
entity_.id as gnbid1_9_,
... // 몇몇 필드는 생략
entity.depth as depth6_9_,
entity.displayEndAt as displaye7_9_,
entity.displayStartAt as displays8_9_,
entity.serviceType as service16_9_
from
v_table entity
where
entity.serviceType=''
and (
entity.displayStartAt < '2021-03-01 12:12:12'
or entity.displayStartAt = '2021-03-01 12:12:12'
)
and (
entity.displayEndAt > '2021-03-12 12:12:12'
or entity.displayEndAt = '2021-03-12 12:12:12'
)
;
# 2번
explain select
entity_.id as gnbid1_9_,
... // 몇몇 필드는 생략
entity.depth as depth6_9_,
entity.displayEndAt as displaye7_9_,
entity.displayStartAt as displays8_9_,
entity.serviceType as service16_9_
from
v_table entity
where
entity.serviceType=''
and (
entity.displayEndAt > '2021-03-12 12:12:12'
or entity.displayEndAt = '2021-03-12 12:12:12'
)
;
나는 이 쿼리를 효율적으로 하기 위해서,
displayStartAt에 idx도 걸어보았고, 별개로 displayEndAt에도 idx를 걸어보았는데,
이상하게도 displayStartAt idx는 타면서 EndAt으로 만든 idx는 타지 않는 현상을 맛보게 된다....
망할.... 이유는 결국 찾지 못했다.
대신 (serviceType, displayEndAt) 으로 복합 인덱스를 생성하니 그제서야 2번째 쿼리가 복합 인덱스를 탔다.
이유가 뭘까...?