Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Query processing: selection, sorting and joins

How DBMS evaluates selections, sorts and joins: definitions, I/O cost formulas, step-by-step derivations, worked numeric examples and exam tips for comparing algorithms (nested-loop, sort-merge, hash, external sort, index lookups).

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Database engines must choose how to get the data a query asks for. Selection, sorting and join algorithms determine query speed and resource use (CPU, memory, disk). Engineers use these costs to build query plans, pick indexes and tune buffer allocation.

Key ideas

  • Full (linear) scan: read all pages of relation R once. Cost = N_R page reads.

  • Index selection: use an index to locate qualifying tuples. If the index is clustered (tuples in disk order of index), cost ≈ index-height + output-pages. If unclustered, each qualifying tuple may require a separate I/O (worst-case: one I/O per tuple). State assumptions: index stored as B+ tree; data pages contain multiple tuples. If the query is covered by the index (index-only scan), qualifying tuples can be returned from index leaf pages without fetching data pages; cost is then roughly index height plus the number of leaf pages touched.

  • Sorting: external sort (external merge sort) is the usual method when data does not fit in RAM. Steps: (1) Make initial sorted runs by reading B pages, sorting in memory, writing runs; (2) Merge runs repeatedly with a (B-1)-way merge (reserve one page for output). The cost is driven by number of passes over the data. Rule of thumb: a two-pass sort is possible when ceil(N / B) ≤ B - 1 (approximately N ≤ B · (B - 1)), giving total cost 4 · N I/Os.

    • Derivation (standard): Let N be pages, B buffers.
      • Initial runs = R0 = ceil(N / B). Each initial pass reads then writes the whole relation: 2·N I/Os.
      • Merge degree = B - 1 (reserve one buffer for output). Number of merge passes P = ceil(log_{B-1}(R0)). Each pass reads and writes N pages: 2·N per pass.
      • Total I/O = 2·N · (1 + P).
  • Joins: combining tuples from two relations R and S. Main algorithms and their I/O cost (measure in page reads/writes). Symbols below: N_R = pages of R, N_S = pages of S, B = buffer pages, T_R = tuples in R when needed. Unless otherwise stated, I/O costs ignore writing the final output (result) and count only reads/writes of inputs and intermediates.

    • Simple nested-loop join (tuple-at-a-time): For each tuple r in R, scan S to find matches. Cost (pages) ≈ N_R + T_R · N_S (if tuple causes full scan); usually too expensive.

    • Block nested-loop join: Use B buffers. Reserve one output buffer and one for S input, so you can load B-2 pages of R at a time. Number of R-chunks = ceil(N_R / (B-2)). Cost = N_R + ceil(N_R / (B-2)) · N_S. Choose the smaller relation as the outer to reduce cost.

    • Index nested-loop join: If S has an index on the join key, for each tuple of R probe the index to find matches. Cost ≈ N_R + T_R · cost(index probe). For clustered index, fewer I/Os; for unclustered, expensive random I/Os.

    • Sort-merge join: Sort R and S (cost_sort(R) + cost_sort(S)), then one sequential merge pass: + N_R + N_S. So total = cost_sort(R) + cost_sort(S) + N_R + N_S. Uses sorted order on join key.

    • Hash join (partitioned): Two phases. Partition both relations into k partitions using a hash of the join key (read each relation and write partitions: 2·(N_R + N_S)). Then for each partition, load smaller partition in memory and probe the other: reading partitions again adds (N_R + N_S). If partition sizes fit memory during build/probe, total I/O ≈ 3·(N_R + N_S). Assumptions: hash function, enough buffers to make partitions small enough; no skew. In practice, a two-pass (non-recursive) hash join is possible if the largest build-side partition fits in memory: ceil(N_build / (B - 1)) ≤ B - 2 (approximately N_build ≤ (B - 1) · (B - 2)), where N_build is the number of pages of the chosen build input; otherwise recursive partitioning or hybrid hashing is required.

  • Choosing algorithms: use indexes when selective; use hash join for equality joins if memory allows; use sort-merge if both inputs already sorted or when merge needed for ORDER BY.

  • Diagrams to draw in exams: for external sort, draw timeline of passes: input → initial runs (label run size B pages) → k-way merge steps, label how many passes; for block nested-loop join, draw buffers: B buffers, show B-2 loaded pages of R, one page for S scanning, one output page.

Formulas

Selectivity s = #qualifying_tuples / #total_tuples — s is unitless, applies to selectivity estimates.

Output_pages = ceil(s · N) — N is pages of relation; applies when selectivity and page-fill known.

ExternalSort_I/O = 2·N · (1 + ceil(log_{B-1}(ceil(N / B)))) — N pages, B buffer pages, assumes one output buffer reserved, applies to external merge sort.

BlockNestedLoop_I/O = N_outer + ceil(N_outer / (B - 2)) · N_inner — N_outer and N_inner measured in pages; B ≥ 3; assumes output cost negligible.

HashJoin_I/O ≈ 3 · (N_R + N_S) — applies when partitioning + build/probe each require scanning each relation once and partitions fit memory for in-memory build-probe per partition.

SortMergeJoin_I/O = ExternalSort_I/O(R) + ExternalSort_I/O(S) + (N_R + N_S) — applies when neither input is pre-sorted; cost in pages.

IndexSelection_I/O ≈ height(index) + output_pages (clustered index) — height(index) is index tree levels read; output_pages depends on selectivity. For unclustered index, additional factor: may be up to one I/O per matching tuple.

Worked examples

Example 1 — External sort cost Problem: Relation size N = 2000 pages, buffers B = 21 pages. Compute external sort I/O. Steps:

  1. Initial runs R0 = ceil(2000 / 21) = ceil(95.238...) = 96 runs.
  2. Merge degree = B - 1 = 20. Number of merge passes P = ceil(log_{20}(96)). Since 20^1 = 20 < 96 and 20^2 = 400 > 96, P = 2.
  3. Total I/O = 2 · N · (1 + P) = 2 · 2000 · (1 + 2) = 2 · 2000 · 3 = 12,000 page I/Os. Answer: 12,000 page I/Os.

Example 2 — Compare joins Problem: R = 10,000 pages, S = 500 pages, B = 101 buffers. Compute block nested-loop (choose outer R and outer S), hash join (best case), sort-merge join. Steps:

  1. Block nested-loop, outer = R: B-2 = 99; chunks = ceil(10000 / 99) = ceil(101.0101) = 102. Cost = N_R + chunks · N_S = 10000 + 102 · 500 = 10000 + 51,000 = 61,000 pages.
  2. Block nested-loop, outer = S: chunks = ceil(500 / 99) = ceil(5.0505) = 6. Cost = 500 + 6 · 10000 = 500 + 60,000 = 60,500 pages.
  3. Hash join (assume ideal two-phase partitioning, partitions fit): Cost ≈ 3 · (N_R + N_S) = 3 · (10,000 + 500) = 3 · 10,500 = 31,500 pages.
  4. Sort-merge join: compute ExternalSort_I/O for each.
    • For R: R0 = ceil(10000 / 101) = ceil(99.0099) = 100. Merge degree = 100 => P_R = ceil(log_{100}(100)) = 1. Cost_sort(R) = 2·10000·(1 + 1) = 40,000.
    • For S: R0 = ceil(500 / 101) = 5, P_S = ceil(log_{100}(5)) = 1. Cost_sort(S) = 2·500·(1 + 1) = 2,000.
    • Merge pass = N_R + N_S = 10,500. Total = 40,000 + 2,000 + 10,500 = 52,500 pages. Conclusion: In this example hash join (31,500) is best; block nested-loop is worst. State assumptions (no skew, enough memory for hash partitions, output cost ignored).

Common mistakes

  • Forgetting the initial read+write (2·N) when computing external sort passes.
  • Treating index lookups like scans (ignoring clustered vs unclustered behavior).
  • Forgetting ceil( ) when dividing pages; leads to underestimates.
  • Not stating assumptions (e.g., enough buffers, no skew, output size negligible).

For your exam

Question types: definitions (selectivity, clustered index), short notes (compare join methods), derivations (external sort I/O formula), numericals (compute I/O cost for given N, B), trace algorithms (simulate a small hash join or merge), diagrams (buffers layout).

What a full-marks answer includes:

  • Clear definitions of terms used (pages, selectivity, clustered/unclustered).
  • Statement of assumptions (page size, buffers, whether indexes clustered, tuple sizes, whether output pages counted).
  • Correct formula(s) with derivation steps (e.g., show why external sort has P passes and why each pass costs 2·N).
  • Correct numeric computation with ceil() shown and final units (page I/Os).
  • Short justification for choosing one join algorithm over another (memory, pre-sorted input, index availability).

Quick check

  1. If relation R has 100 pages and selectivity s = 0.1, how many pages expected in output?
  2. External sort: N = 5,000 pages, B = 51 buffers. Initial runs = ?
  3. Block nested-loop join: N_R = 2000 pages, N_S = 500 pages, B = 22 buffers; using R as outer, number of chunks = ? Answers: 1) 10 pages (ceil(0.1·100) = 10). 2) ceil(5000 / 51) = ceil(98.039...) = 99 initial runs. 3) B-2 = 20; chunks = ceil(2000 / 20) = ceil(100) = 100.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?