1. Gyanastra
  2. Database Systems
  3. Join Order, Merge Join Seek-Transfer Model and Non-Key Index Join
  4. 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 rr (outer) and ss (inner), with MM buffer blocks:

b=br+⌈brM−2⌉⋅bs,s=2⌈brM−2⌉b = b_r + \left\lceil \frac{b_r}{M-2} \right\rceil \cdot b_s, \qquad s = 2\left\lceil \frac{b_r}{M-2} \right\rceil

The M−2M-2 is because one block is reserved for the current block of the inner relation and one for the output; the remaining M−2M-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\boxed{b = b_r + b_s, \qquad 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 rr have br=400b_r = 400 blocks, nr=40,000n_r = 40{,}000 tuples; ss have bs=100b_s = 100 blocks, ns=10,000n_s = 10{,}000 tuples. Memory M=120M = 120 blocks. tT=1t_T = 1 ms, tS=10t_S = 10 ms.

Check fit: smaller is ss with bs=100b_s = 100. Need bs≤M−2=118b_s \le M - 2 = 118. Yes, 100≤118100 \le 118. So ss fits.

Cost (fits case):

  • b=br+bs=400+100=500b = b_r + b_s = 400 + 100 = 500 transfers.
  • s=2s = 2 seeks.
  • Total =500⋅1+2⋅10=500+20=520= 500 \cdot 1 + 2 \cdot 10 = 500 + 20 = 520 ms.

Compare with general block nested-loop (outer =s= s, since ss is smaller, ⌈bs/(M−2)⌉=⌈100/118⌉=1\lceil b_s/(M-2)\rceil = \lceil 100/118 \rceil = 1):

  • b=bs+1⋅br=100+400=500b = b_s + 1 \cdot b_r = 100 + 400 = 500 — same, because one chunk already covers all of ss.
  • s=2⋅1=2s = 2 \cdot 1 = 2 seeks. Same.

So when the smaller relation fits, both formulas collapse to br+bsb_r + b_s and 2 seeks. This is the key exam fact: if the smaller relation fits in memory, block nested-loop join costs br+bsb_r + b_s transfers and 2 seeks.

If it did NOT fit (say M=50M = 50, so M−2=48M - 2 = 48, and bs=100>48b_s = 100 > 48): outer =s= s, ⌈100/48⌉=⌈2.083⌉=3\lceil 100/48 \rceil = \lceil 2.083 \rceil = 3 chunks:

  • b=100+3⋅400=100+1200=1300b = 100 + 3 \cdot 400 = 100 + 1200 = 1300 transfers.
  • s=2⋅3=6s = 2 \cdot 3 = 6 seeks.
  • Total =1300+60=1360= 1300 + 60 = 1360 ms — much worse. This shows why "fits in memory" matters.

Pages 1–2 of 2