Foreign key

외래 키

The database checks that a child row points to an existing parent row.

···
html
<div class="demo"><div class="head"><b>FOREIGN KEY</b><span>orders.customer_id</span></div><div class="stage fk"><div class="cell parent">customer 7</div><div class="wire">────→</div><div class="cell child">order 51</div></div><div class="foot"><span id="fkstatus">DELETE customer 7: blocked</span><span id="fkmark">referenced</span></div></div>
css
*{box-sizing:border-box}.demo{width:min(96vw,820px);height:min(94vh,350px);padding:clamp(8px,2vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);color:var(--fg);display:flex;flex-direction:column;gap:clamp(5px,1.5vmin,12px);font:600 clamp(12px,3.5vmin,15px)/1.25 var(--font-sans),sans-serif;overflow:hidden}.head,.foot,.row{display:flex;justify-content:space-between;align-items:center;gap:8px}.head b{color:var(--accent)}.head span,.foot,.muted{color:var(--muted)}.stage{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;gap:8px}.cell,.pill{border:1px solid var(--line);border-radius:8px;background:var(--bg);padding:clamp(4px,1.2vmin,9px);text-align:center}.pill{border-radius:999px}.on{border-color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 17%,var(--surface))!important;color:var(--fg)!important}.bad{border-color:#e16a5d!important;background:color-mix(in srgb,#e16a5d 18%,var(--surface))!important}.foot{font-size:clamp(12px,3vmin,14px)}.fk{justify-content:center}.parent,.child{min-width:30%}.wire{color:var(--accent);white-space:nowrap}.parent,.child{transition:.3s}
js
let n=0;function tick(){document.querySelector('.parent').classList.toggle('bad',!n);document.querySelector('.child').classList.toggle('on',!!n);document.getElementById('fkstatus').textContent=n?'order 51 references 7':'DELETE customer 7: blocked';document.getElementById('fkmark').textContent=n?'valid link':'referenced';n=1-n}tick();const t=setInterval(tick,1100);document.querySelector('.demo').onclick=()=>{clearInterval(t);tick()}

A foreign key requires a value in a child table to refer to a candidate key in the parent table. The database rejects invalid references.

Deleting a parent applies the configured action, such as restriction, cascade, or setting a default. The demo shows deletion being blocked while an order still refers to a customer. Choose cascade only after checking its impact.

When to use

Use it when the database should enforce referential integrity between tables.

Open as page ↗