220516
데이터베이스의 테이블에 대한 검색 속도를 향상시켜주는 자료구조
특정 컬럼
에 생성되는 검색 도구미리 정렬
★★★ > 인덱스-- num(PK), name(일반컬럼)
select num from tblInsa; -- 속도 동일
select name from tblInsa; -- 속도 동일
-- where절이 붙어야 색인
select * from tblInsa where num = 1001; -- 속도 빠름(PK)
select * from tblInsa where name = '홍길동'; -- 속도 느림
create table tblIndex
as
select * from tblInsa;
select * from tblIndex;
select count(*) from tblIndex; -- 7602176건
insert into tblIndex select * from tblIndex; -- 더미 데이터 생성
-- 시간 확인
set timing on;
-- SQL 실행
-- 1. Ctrl + Enter > 결과 > 테이블 출력
-- 2. F5 > 결과 > 텍스트 출력
-- 인덱스 없이 검색 00:00:00.597
select distinct name from tblIndex where name = '홍길동';
-- !인덱스 생성
create index idxName on tblIndex(name);
-- 인덱스 사용해서 검색 00:00:00.103
select distinct name from tblIndex where name = '홍길동';
테이블에 데이터(행)가 너무 많을 때
where절에 사용되는 횟수가 많은 컬럼
★★★
join에 사용되는 컬럼 (ON 부모.PK=자식.FK)
★★★
인덱스의 손익분기점 > 검색 결과가 10~15% 이하인 경우
null을 포함하는 경우 (null 인덱스에서 제외)
테이블에 데이터(행)가 적은 경우 > 의미 없기 때문에
인덱스의 손익분기점 > 검색 결과가 15% 이상인 경우
해당 테이블의 삽입, 수정, 삭제가 빈번할 경우
★★★
- 고유 인덱스
- 비고유 인덱스
- 단일 인덱스
- 복합 인덴스
- 함수 기반 인덱스
- ...
-- 고유 인덱스
-- : 색인의 값이 중복이 불가능하다.
-- : PK, UNIQUE
create unique index idxBuseo on tblIndex(buseo); -- 동명이인(X)
-- 비고유 인덱스
-- : 색인의 값이 중복이 가능하다.
-- : 일반 컬럼
create index idxBuseo on tblIndex(buseo);
-- 단일 인덱스
-- : 컬럼 1개를 대상
create index idxBuseo on tblIndex(buseo);
select count(*) from tblIndex where buseo = '기획부'; -- 인덱스 효과 O
select count(*) from tblIndex where buseo = '기획부' and name = '홍길동'; -- 인덱스 효과 X
-- 복합(결합) 인덱스
-- : 컬럼 N개를 대상
create index idxBuseoName on tblIndex(buseo, name);
select count(*) from tblIndex where buseo = '기획부' and name = '홍길동'; -- 인덱스 효과 O
select count(*) from tblIndex where name = '홍길동' and buseo = '기획부'; -- 인덱스 효과 O
-- where절에 상태에 따라 달라짐
-- 함수 기반 인덱스
create index idxSsn on tblIndex(ssn); -- 인덱스 효과 X
create index idxSsn on tblIndex(substr(ssn, 8, 1));
select count(*) from tblIndex where substr(ssn, 8, 1) = '1';