Algorithm Search⌘K

Techniqueadvanced

What-if index analysis

Also called hypothetical indexes, what-if optimizer calls.

Estimate the benefit of an index without building it by giving the optimizer statistics of a hypothetical index and costing the plans.

What-if index analysis asks the query optimizer what a query would cost if some indexes existed, without building them. The optimizer of a relational database chooses plans by a cost model that reads only the metadata of an index (its columns, its number of entries and pages, its height) and the statistics of its columns, such as a histogram. It never reads the index data while it plans. So a tool can add a hypothetical index to the catalog, with metadata computed from the table size and statistics built from a sample, call the optimizer, and read the cost and the plan. Building the real index needs a sort of the whole table; a hypothetical one needs a small sample. Chaudhuri and Narasayya made this interface for SQL Server in 1998, and index advisors such as the AutoAdmin tool get all their costs this way.

In plain words

Before you buy a new shelf for a shop, you want to know how much time it would save. You do not build it to find out. You tell the planner "imagine a shelf here, this tall, with these items", and the planner works out the new walking routes on paper. The planner only ever looks at the drawing and at counts of the items, never at a real shelf, so the answer on paper is the same as the answer with a real shelf. Then you rub the drawing out.

The counts are the weak point. If you count only a sample of the items, the planner's answer can be off, most of all for rare items.

When it applies

  • The optimizer is cost-based, and its cost model uses only metadata and statistics of indexes, not their contents.
  • Many index configurations must be compared, as in index selection, and building each one would take far too long or disturb the running system.
  • The question is a comparison of plans and costs, not a measured run time. What-if analysis answers "what would the optimizer do", which is also the plan the system would run.

The template

  1. WHAT-IF(Q, C) ▷ the cost and plan of query Q if the hypothetical indexes C existed
  2. 1for each index h in C that does not exist: add to the catalog its metadata (columns, entries, pages, height), marked hypothetical
  3. 2build the statistics of the columns of h from a sample of the table
  4. 3(plan, cost) ← OPTIMIZE(Q) ▷ the optimizer sees the real and the hypothetical indexes, and runs nothing
  5. 4remove the hypothetical metadata and statistics from the catalog; return (plan, cost)

A call can also hide real indexes, so that a tool can ask what happens if an index is dropped. The hypothetical indexes must be visible only to the optimizer calls of the tool, so that no other query ever plans with them.

Why it is exact for the optimizer. The cost of a plan is a function of the metadata and the statistics alone. If a hypothetical index gets the same metadata and statistics as the real index would have, the optimizer gives the same plan and the same cost for it as for the real index. Only the statistics from a sample can differ, and that difference is the only error of the method, besides the error of the cost model itself.

Cost. The metadata of a B+ tree follow from the table size and the key width: ⌈N/L⌉\lceil N / L \rceil leaf pages for LL entries per leaf and a height of about log⁡F\log_F of that for fanout FF. A sample of ss rows costs O(slog⁡s)O(s \log s) to make a histogram from, against Θ(Nlog⁡N)\Theta(N \log N) to build the index. Each call then costs one optimization.

Classic examples

These come from the code on this page: a table of N=100,000N = 100{,}000 rows (seed 7), 50 rows per page, so a full scan reads 2,000 pages; a B+ tree with 200 entries per leaf and fanout 200, so 500 leaf pages and height 3; histograms with 20 buckets; and one page read per row fetched by an index.

query on column aa (uniform) what-if, 5% sample what-if, all rows with the built index pages read when run
1000≤a≤19991000 \le a \le 1999 (101 rows) index, 106.4 index, 102.1 index, 102.1 104
0≤a≤499990 \le a \le 49999 (4,961 rows) scan, 2,000 scan, 2,000 scan, 2,000 2,000

The what-if call with a 5% sample read 5,000 rows; building the index read all 100,000 and sorted them. With statistics from all rows, the hypothetical cost equals the cost with the built index exactly, as the template says, and the tests check this on 200 random queries over two columns. The estimate is a measurement of the cost model, so it can differ from the pages a run reads (102.1 against 104).

Skewed data. On a second column with a heavy-tailed (Pareto) distribution, over 300 small range queries, the median ratio of the sampled estimate to the pages read was 1.0. For 10% of the queries the estimate was more than 2.8 times too large, and in the worst case it was about 100 times too small (a measurement). A 5% sample sees too few rows of the rare values.

Index advisors. The AutoAdmin tool of SQL Server makes thousands of what-if calls to compare configurations, and reduces their number with atomic configurations. Later tools work the same way, and the PostgreSQL extension HypoPG adds hypothetical indexes for the same purpose.

Variations

  • Hiding indexes. A call can pretend that a real index is gone, to estimate the effect of dropping it.
  • Other structures. The same idea applies to materialized views (view selection), partitionings and partial indexes: anything whose effect on the optimizer goes through metadata and statistics.
  • Virtual indexes. Some systems store hypothetical indexes in the catalog with no storage, for example Oracle's NOSEGMENT indexes, so that the normal EXPLAIN uses them.
  • Statistics reuse. Indexes with the same leading column share the statistics of that column, so a tool builds them once.
  • Plan inspection. Besides the cost, a call returns the plan, so a tool can see which indexes a query uses and build reports, such as which queries an index would serve.

Pitfalls

  • Bad statistics. The estimate is only as good as the statistics. A small sample misses rare values and the tail of a skewed column; correlated columns break the independence assumption of the cardinality estimates. The what-if cost can then be far from the real one.
  • The cost model is not the run time. A what-if call says what the optimizer believes, not what will happen. Caching, concurrency and the real layout of the data on disk are not in the estimate. Check important choices with real runs.
  • Missing maintenance cost. A select-only what-if call does not show the cost of keeping the index up to date. Include the inserts, updates and deletes of the workload.
  • Leaking hypothetical indexes. If a hypothetical index stays in the catalog, other sessions can get plans that use an index that does not exist. Keep them private to the session of the tool and remove them after the call.
  • Too many calls. Each call is a full optimization. A tool that costs every configuration of every query makes far too many calls; derive costs from those of smaller configurations where the optimizer model allows it.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

what_if_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/what-if-index-analysis/. The authors are listed in prov/STWF16.jsonl.

"""What-if index analysis (Chaudhuri and Narasayya, SIGMOD 1998), on a toy
optimizer.

The optimizer never looks at index data. It costs a plan from metadata (the
number of entries, leaf pages and the height of the index) and from the
statistics of the column (an equi-depth histogram). So an index can be made
"hypothetical": the catalog gets its metadata and statistics, built from a
sample, and no index is built. A what-if call adds such indexes to the
catalog for one optimization and then removes them.
"""

import math
import random
from bisect import bisect_left, bisect_right
from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple

ROWS_PER_PAGE = 50
ENTRIES_PER_LEAF = 200
FANOUT = 200


class Histogram:
    """An equi-depth histogram: the bucket bounds of sorted values."""

    def __init__(self, values: Sequence[int], buckets: int, total: int):
        v = sorted(values)
        self.total = total
        self.bounds = [v[min(len(v) - 1, (i * len(v)) // buckets)] for i in range(buckets)] + [v[-1]]
        self.buckets = buckets

    def selectivity(self, lo: int, hi: int) -> float:
        """The estimated fraction of rows with lo <= value <= hi."""
        f = 0.0
        for i in range(self.buckets):
            a, b = self.bounds[i], self.bounds[i + 1]
            width = b - a + 1
            ov = min(b, hi) - max(a, lo) + 1
            if ov > 0:
                f += ov / width / self.buckets
        return min(1.0, f)


@dataclass
class IndexMeta:
    column: str
    entries: int
    leaf_pages: int
    height: int
    hypothetical: bool


def btree_shape(n: int) -> Tuple[int, int]:
    """The leaf pages and the height of a bulk-loaded B+ tree with n entries."""
    leaves = max(1, math.ceil(n / ENTRIES_PER_LEAF))
    height, level = 1, leaves
    while level > 1:
        level = math.ceil(level / FANOUT)
        height += 1
    return leaves, height


class BuiltIndex:
    """A real index: the sorted (value, row id) pairs, in pages."""

    def __init__(self, table: "Table", column: str):
        self.column = column
        self.entries = sorted((r[column], i) for i, r in enumerate(table.rows))
        self.leaves = [self.entries[i:i + ENTRIES_PER_LEAF]
                       for i in range(0, len(self.entries), ENTRIES_PER_LEAF)] or [[]]
        # build the upper levels to get the real height
        level, height = len(self.leaves), 1
        while level > 1:
            level = math.ceil(level / FANOUT)
            height += 1
        self.height = height
        table.rows_read += len(table.rows)

    def meta(self) -> IndexMeta:
        return IndexMeta(self.column, len(self.entries), len(self.leaves), self.height, False)


class Table:
    def __init__(self, rows: List[Dict[str, int]]):
        self.rows = rows
        self.rows_read = 0

    def sample(self, column: str, fraction: float, seed: int) -> List[int]:
        if fraction >= 1.0:
            self.rows_read += len(self.rows)
            return [r[column] for r in self.rows]
        rng = random.Random(seed)
        k = max(1, int(fraction * len(self.rows)))
        idx = rng.sample(range(len(self.rows)), k)
        self.rows_read += k
        return [self.rows[i][column] for i in idx]


class Optimizer:
    def __init__(self, table: Table, buckets: int = 20):
        self.table = table
        self.buckets = buckets
        self.catalog: Dict[str, IndexMeta] = {}
        self.stats: Dict[str, Histogram] = {}
        self.built: Dict[str, BuiltIndex] = {}

    # ----- real indexes -----

    def create_index(self, column: str) -> None:
        ix = BuiltIndex(self.table, column)
        self.built[column] = ix
        self.catalog[column] = ix.meta()
        self.stats[column] = Histogram([e[0] for e in ix.entries], self.buckets, len(ix.entries))

    # ----- costing (metadata and statistics only) -----

    def cost(self, column: str, lo: int, hi: int) -> Tuple[float, str]:
        """The cheapest plan for lo <= column <= hi, and its cost in pages."""
        n = len(self.table.rows)
        best, plan = math.ceil(n / ROWS_PER_PAGE), "scan"
        meta = self.catalog.get(column)
        if meta is not None:
            if column not in self.stats:
                raise KeyError("no statistics for " + column)
            rows = self.stats[column].selectivity(lo, hi) * n
            c = (meta.height - 1) + max(1.0, rows / ENTRIES_PER_LEAF) + rows   # one page per row fetched
            if c < best:
                best, plan = c, "index"
        return best, plan

    # ----- the what-if call -----

    def what_if(self, query: Tuple[str, int, int], hypothetical: Sequence[str],
                fraction: float = 0.05, seed: int = 0) -> Tuple[float, str]:
        column, lo, hi = query
        saved_cat, saved_stats = dict(self.catalog), dict(self.stats)
        try:
            for col in hypothetical:
                if col in self.catalog:
                    continue
                leaves, height = btree_shape(len(self.table.rows))              # @line L1
                self.catalog[col] = IndexMeta(col, len(self.table.rows), leaves, height, True)   # @line L1
                values = self.table.sample(col, fraction, seed)                  # @line L2
                self.stats[col] = Histogram(values, self.buckets, len(self.table.rows))   # @line L2
            return self.cost(column, lo, hi)                                     # @line L3
        finally:
            self.catalog, self.stats = saved_cat, saved_stats                    # @line L4

    # ----- running a plan -----

    def run(self, column: str, lo: int, hi: int) -> Tuple[List[int], int]:
        """Run the chosen plan with the built indexes. Returns row ids and pages read."""
        _, plan = self.cost(column, lo, hi)
        if plan == "index":
            ix = self.built[column]
            i = bisect_left(ix.entries, (lo, -1))
            j = bisect_right(ix.entries, (hi, math.inf))
            leaves = max(1, math.ceil((j - i) / ENTRIES_PER_LEAF))
            return sorted(rid for _, rid in ix.entries[i:j]), (ix.height - 1) + leaves + (j - i)
        out = [i for i, r in enumerate(self.table.rows) if lo <= r[column] <= hi]
        return out, math.ceil(len(self.table.rows) / ROWS_PER_PAGE)


def full_scan(table: Table, column: str, lo: int, hi: int) -> List[int]:
    return [i for i, r in enumerate(table.rows) if lo <= r[column] <= hi]
test_what_if_index.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/what-if-index-analysis/. The authors are listed in prov/STWF16.jsonl.

import random
import statistics
import unittest

from what_if_index import Optimizer, Table, full_scan


def make_table(n, seed):
    rng = random.Random(seed)
    return Table([{"a": rng.randrange(10 ** 6), "b": int(rng.paretovariate(1.2)) % 5000}
                  for _ in range(n)])


def random_query(rng, col):
    lo = rng.randrange(10 ** 6) if col == "a" else rng.randrange(50)
    width = rng.choice([10, 100, 1000, 10 ** 4, 10 ** 5]) if col == "a" else rng.randrange(0, 20)
    return col, lo, lo + width


class TestAgainstBuiltIndex(unittest.TestCase):
    def test_full_statistics_give_the_cost_of_the_built_index(self):
        """With statistics from all rows, the what-if cost equals the cost with the real index."""
        rng = random.Random(1)
        t = make_table(20000, 1)
        hypo = Optimizer(t)
        real = Optimizer(t)
        real.create_index("a")
        real.create_index("b")
        for _ in range(200):
            q = random_query(rng, rng.choice("ab"))
            self.assertEqual(hypo.what_if(q, [q[0]], fraction=1.0), real.cost(*q))

    def test_what_if_leaves_the_catalog_unchanged(self):
        t = make_table(5000, 2)
        opt = Optimizer(t)
        self.assertEqual(opt.cost("a", 10, 20)[1], "scan")
        c, plan = opt.what_if(("a", 10, 20), ["a"])
        self.assertEqual(plan, "index")
        self.assertEqual(opt.catalog, {})
        self.assertEqual(opt.stats, {})
        self.assertEqual(opt.cost("a", 10, 20)[1], "scan")

    def test_what_if_reads_only_a_sample(self):
        t = make_table(20000, 3)
        opt = Optimizer(t)
        opt.what_if(("a", 0, 100), ["a"], fraction=0.05)
        self.assertEqual(t.rows_read, 1000)
        opt.create_index("a")
        self.assertEqual(t.rows_read, 21000)


class TestAgainstFullScan(unittest.TestCase):
    def test_plans_on_built_indexes_return_the_scan_result(self):
        rng = random.Random(4)
        t = make_table(20000, 4)
        opt = Optimizer(t)
        opt.create_index("a")
        opt.create_index("b")
        plans = set()
        for _ in range(100):
            q = random_query(rng, rng.choice("ab"))
            rows, pages = opt.run(*q)
            plans.add(opt.cost(*q)[1])
            self.assertEqual(rows, full_scan(t, *q))
        self.assertEqual(plans, {"index", "scan"})

    def test_sampled_estimates_are_close_to_the_real_cost(self):
        """A measurement: on uniform data, a 5% sample predicts the pages read well."""
        rng = random.Random(5)
        t = make_table(20000, 5)
        opt = Optimizer(t)
        real = Optimizer(t)
        real.create_index("a")
        ratios = []
        for _ in range(200):
            col, lo, _ = random_query(rng, "a")
            q = (col, lo, lo + 10 ** 4)                  # about 1% of the rows
            est, plan = opt.what_if(q, ["a"], fraction=0.05, seed=rng.randrange(100))
            if plan == "index":
                _, pages = real.run(*q)
                ratios.append(est / pages)
        self.assertGreater(len(ratios), 150)
        self.assertLess(abs(statistics.median(ratios) - 1.0), 0.2)


if __name__ == "__main__":
    unittest.main()

Exercises

  1. A table has 10710^7 rows; a leaf holds 300 entries and an inner page 300 children. Compute the leaf pages and the height of the hypothetical index that L1 puts in the catalog.
  2. Show that if the cost of every plan depends only on metadata and statistics, a hypothetical index with exact statistics gets the same plan and cost as the real index.
  3. A column has 1,000,000 rows, and one value occurs in 50 of them. What is the chance that a uniform sample of 5% contains none of those rows? What does the optimizer then estimate for an equality query on that value, and what would it choose?

References

  1. Surajit Chaudhuri and Vivek Narasayya, AutoAdmin what-if index analysis utility, Proceedings of ACM SIGMOD 1998, pp. 367 to 378, hypothetical indexes with metadata and sampled statistics only, the interface that makes the optimizer cost a query under a chosen configuration, and the analysis of workloads with it
  2. Surajit Chaudhuri and Vivek Narasayya, An efficient, cost-driven index selection tool for Microsoft SQL Server, Proceedings of VLDB 1997, pp. 146 to 155, the index selection tool that gets all its costs from the optimizer and reduces the number of these calls

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples