Database index

데이터베이스 인덱스

A sorted lookup structure narrows the search for rows instead of scanning the whole table.

···
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()})

An index stores search keys and row locations in a separate structure. Many relational databases use a B-tree family index to narrow the range level by level, then fetch matching rows.

The demo finds key 42 by taking the branch below 50 and then reaching its leaf. Indexes can speed reads but consume storage and add update work to writes.

When to use

Inspect the query plan and consider an index when repeated WHERE, JOIN, or sort queries are slow.

Open as page ↗