Nested-Loop Join When the Smaller Relation Fits in Memory
Free lesson, no account needed 4 min read
Database Systems · Join Order, Merge Join Seek-Transfer Model and Non-Key Index Join
Nested-Loop Join When the Smaller Relation Fits in Memory
2.1 Block nested-loop join, general cost
For relations r (outer) and s (inner), with M buffer blocks:
b=br+⌈M−2br⌉⋅bs,s=2⌈M−2br⌉
The M−2 is because one block is reserved for the current block of the inner relation and one for the output; the remaining M−2 blocks hold the outer chunk.
2.2 The "fits in memory" special case
If the smaller relation fits entirely in memory, we load it once and stream the other relation once. Then:
b=br+bs,s=2
(one seek to start reading each relation; the loaded relation is read once, the streamed relation is read sequentially once). This is the cheapest possible for a block nested-loop join and is the number GATE expects when it says "the smaller relation fits in memory."
2.3 Worked example
Let r have br=400 blocks, nr=40,000 tuples; s have bs=100 blocks, ns=10,000 tuples. Memory M=120 blocks. tT=1 ms, tS=10 ms.
Check fit: smaller is s with bs=100. Need bs≤M−2=118. Yes, 100≤118. So s fits.
Cost (fits case):
b=br+bs=400+100=500 transfers.
s=2 seeks.
Total =500⋅1+2⋅10=500+20=520 ms.
Compare with general block nested-loop (outer =s, since s is smaller, ⌈bs/(M−2)⌉=⌈100/118⌉=1):
b=bs+1⋅br=100+400=500 — same, because one chunk already covers all of s.
s=2⋅1=2 seeks. Same.
So when the smaller relation fits, both formulas collapse to br+bs and 2 seeks. This is the key exam fact:if the smaller relation fits in memory, block nested-loop join costs br+bs transfers and 2 seeks.
If it did NOT fit (say M=50, so M−2=48, and bs=100>48): outer =s, ⌈100/48⌉=⌈2.083⌉=3 chunks:
b=100+3⋅400=100+1200=1300 transfers.
s=2⋅3=6 seeks.
Total =1300+60=1360 ms — much worse. This shows why "fits in memory" matters.