INDEX란?
InnoDB의 인덱스 구조
MySQL의 스토리지 엔진인 InnoDB의 경우 B+Tree 자료구조로 구성되어 있다.(B-Tree의 확장 개념)
INDEX의 종류
인덱스는 언제 사용하는가?
INDEX 따로 추가하기
-- UNIQUE KEY 추가: studentId 컬럼에는 중복값이 들어갈 수 없다.
ALTER TABLE `student` ADD UNIQUE INDEX `index_studentId` (`studentId`) USING BTREE;
-- 일반 인덱스 추가
ALTER TABLE `student` ADD INDEX `idx_department` (`department`);
-- 일반 복합 인덱스 추가
ALTER TABLE `student` ADD INDEX `idx_department_address` (`department`, `address`);
INDEX 삭제하기
ALTER TABLE 테이블명 DROP INDEX 인덱스명
실행 계획(성능) 보기
MySQL의 옵티마이저가 어떻게 판단해서 쿼리를 실행하는지 정보를 본다.
explain 쿼리문;
-- index가 없는 컬럼 like: 인덱스가 없으므로 full scan
explain select * from customer where first_name like 'A%';
explain select * from customer where first_name like '%A';
explain select * from customer where first_name like '%A%';
-- index가 있는 컬럼 like
explain select * from customer where last_name like 'A%'; -- range scan
explain select * from customer where last_name like '%A'; -- full scan
explain select * from customer where last_name like '%A%'; -- full scan
-- pk로 값 조회: const
explain select * from customer where customer_id = 3;
-- index 없는 컬럼 값 조회: full scan
explain select * from film where length = 100;
-- index로 값 조회: ref
explain select * from customer where store_id = 2;
-- pk로 범위 조회
explain select * from film where film_id < 10; -- range
explain select * from film where film_id < 1000; -- range
-- index가 없는 컬럼 범위 조회
explain select * from film where length < 50; -- full scan
-- length 컬럼 index 추가하기
alter table film add index `idx_length` (`length`);
-- index로 범위 조회
explain select * from film where length < 50; -- range
explain select * from film where length < 100; -- full scan --> 데이터 수가 적기 때문에 옵티마이저가 풀스캔이 낫다고 판단
-- index 삭제하기
alter table film drop index `idx_length`;
인덱스 사용시 주의할 점