데이터베이스 인덱스

Database index

정렬된 탐색 구조를 따라 필요한 행의 위치를 찾아 전체 테이블 스캔을 줄입니다.

···
html
<div class="demo"><div class="head"><b>INDEX SEEK</b><span>WHERE id = 42</span></div><div class="tree"><div class="level"><div class="node" id="root">50</div></div><div class="branches">↙ <span>↘</span></div><div class="level"><div class="node" id="left">20 | 40</div><div class="node" id="right">60 | 80</div></div><div class="branches">↙ <span>↘</span></div><div class="level"><div class="node" id="leaf">41 · <b>42</b> · 45</div><div class="node" id="other">61 · 72 · 84</div></div></div><div class="foot"><span id="step">compare at root</span><span>tap to step</span></div></div>
css
.demo{width:min(94vw,690px);height:min(90vh,330px);padding:clamp(8px,2vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:clamp(4px,1.3vmin,10px);font:600 clamp(9px,2.4vmin,15px)/1.2 ui-monospace,monospace}.head,.foot{display:flex;justify-content:space-between;gap:8px}.head b,.node b{color:var(--accent)}.head span,.foot{color:var(--muted)}.foot{font-size:.82em}.tree{flex:1;min-height:0;display:flex;flex-direction:column;justify-content:center;gap:clamp(1px,.5vmin,4px)}.level{display:flex;justify-content:space-around;gap:8px}.node{min-width:28%;text-align:center;border:1px solid var(--line);background:var(--bg);border-radius:7px;padding:clamp(3px,1.1vmin,8px);opacity:.45;transition:opacity .3s,border-color .3s,background .3s}.node.on{opacity:1;border-color:var(--accent);background:color-mix(in srgb,var(--accent) 12%,var(--surface))}.branches{display:flex;justify-content:space-around;color:var(--muted);line-height:1}.branches span{color:var(--line)}
js
const path=['root','left','leaf'],labels=['compare 42 < 50','follow 20 | 40','found row 42'];let step=0;function advance(){document.querySelectorAll('.node').forEach(el=>el.classList.remove('on'));path.slice(0,step+1).forEach(id=>document.getElementById(id).classList.add('on'));document.getElementById('step').textContent=labels[step];step=(step+1)%3}advance();const timer=setInterval(advance,700);document.querySelector('.demo').addEventListener('pointerdown',()=>{clearInterval(timer);advance()})

인덱스는 검색 키와 행의 위치를 별도 구조로 관리합니다. 많은 관계형 데이터베이스는 B-tree 계열 인덱스를 사용해 범위를 단계별로 좁힙니다. 조건에 맞는 키를 찾은 뒤 필요한 행을 읽습니다.

데모는 키 42를 찾기 위해 50보다 작은 가지를 고르고, 다음 노드에서 42가 있는 잎으로 이동합니다. 인덱스는 읽기를 빠르게 할 수 있지만 저장 공간을 차지하고 쓰기 때 갱신 비용이 듭니다.

언제 쓰나

반복되는 WHERE·JOIN·정렬 쿼리가 느릴 때 실행 계획을 보고 적절한 열의 인덱스를 검토합니다.

페이지로 열기 ↗