Algorithm Search⌘K

Techniqueadvanced

Partial index

Also called filtered index.

An index over only the rows that satisfy a predicate, which saves space and update cost when queries target that subset.

A partial index is an ordinary index, such as a B+ tree, that holds entries only for the rows of a table that satisfy a fixed predicate PP, for example status = 'open'. If most queries look only at those rows, and the rows are a small part of the table, the index is much smaller than a full index and most updates do not touch it. The optimizer may use the index for a query only if the query's predicate implies PP, so that no row the query needs can be missing from the index. PostgreSQL calls these partial indexes and SQL Server calls them filtered indexes. A partial unique index makes a key unique only among the rows that satisfy PP.

In plain words

A shop keeps a card for every order it has ever had, sorted by customer. Almost all orders are done, and people only ever ask about the open ones. So the shop keeps a second, small box with a card only for each open order, sorted by customer. When an order is closed, its card leaves the small box; when an old done order is changed, nothing in the small box changes.

To answer "the open orders of customer 120" you look in the small box. To answer "all orders of customer 120" you cannot, because done orders are not in it. You must check first that the question only asks about open orders.

When it applies

  • Queries filter on a condition that holds for a small, stable fraction of the rows: open orders, unprocessed jobs, rows that are not deleted, rows where a column is not null.
  • A full index on the same key would be large, and most writes go to rows outside the subset, so a full index would pay maintenance for rows that queries never ask for.
  • The query predicates are written so that the optimizer can prove that they imply PP. In practice this means that the query repeats the condition of the index, or a narrower one, in the same form.
  • A uniqueness rule holds only for a subset, such as "one active subscription per user".

The template

The index stores (key, row id) pairs for the rows that satisfy PP, in key order. Predicates are conjunctions of comparisons of integer columns with constants. A conjunction allows one closed interval per column, a box. A query on lo≤key≤hilo \le key \le hi with the extra predicate QQ may use the index if the box of Q∧lo≤key≤hiQ \wedge lo \le key \le hi lies inside the box of PP.

  1. BUILD(T, key, P)
  2. 1I ← the sorted pairs (r.key, r.id) for the rows r of T with P(r)
  3. ON-CHANGE(old row o, new row n) ▷ o or n is missing for an insert or a delete
  4. 2if o exists and P(o) then remove (o.key, o.id) from I
  5. 3if n exists and P(n) then insert (n.key, n.id) into I
  6. QUERY(lo ≤ key ≤ hi, Q)
  7. 4if IMPLIES(Q ∧ lo ≤ key ≤ hi, P) then
  8. 5for each (k, id) in I with lo ≤ k ≤ hi do: output id if Q holds for row id
  9. 6else scan T and output the rows with lo ≤ key ≤ hi and Q
  10. IMPLIES(Q, P)
  11. 7for each column c that P restricts do: if the interval of c in Q is not inside the interval of c in P then return false
  12. 8return true ▷ also true if Q allows no row at all

Correctness. L1 to L3 keep the invariant "the index holds exactly the rows that satisfy PP": a change removes the old entry if the old row was in the subset and adds the new entry if the new row is. If the test at L4 succeeds, every row that satisfies the query satisfies PP and so is in the index, and L5 checks QQ on each candidate, so the answer equals that of a full scan. For conjunctions of comparisons on integer columns, the box test of L7 is exact: if the interval of some column in QQ is not inside that of PP, a row with a value in the difference, and any allowed values in the other columns, satisfies QQ but not PP. Real optimizers use a sound but incomplete test on richer predicates, so they sometimes miss a valid use.

Cost. A full index of NN rows costs Θ(N)\Theta(N) entries and an update of every row; a partial index costs Θ(sN)\Theta(sN) entries for a selectivity ss of PP, and only updates of rows that enter, leave or move inside the subset touch it. A query that uses it reads O(log⁡(sN)+t)O(\log(sN) + t) entries for tt matches, as a full index would, plus one check of QQ per candidate.

Classic examples

Open orders. A table of 10,000 orders (seed 2 in the tests) has 514 open ones, with status = 0, and an index on the customer WHERE status = 0 has 514 entries, about 5% of a full index (a measurement).

query, for customers 100 to 199 plan entries or rows read answer
status = 0 partial index 44 44 rows
status = 0 AND amount > 100 partial index, then the check of amount 44 38 rows
no condition on status full scan 10,000 993 rows
status <= 0 full scan 10,000

The last query shows the strictness of the test: as far as the predicate says, status could be negative, so status <= 0 does not imply status = 0. With the condition status >= 0 added to the query, the test succeeds and the index is used. After the index is built, 500 updates of the amount of shipped orders cause no index writes. Closing one open order and reopening one shipped order cause two.

Not null. An index WHERE email IS NOT NULL on a column that is mostly null holds only the rows that have a value, and serves every lookup by email, since email = ? implies email IS NOT NULL.

Partial uniqueness. A unique index on the user WHERE active allows many old subscriptions per user but only one active one. The rule cannot be written as a unique index on the whole table.

Soft deletes. An index WHERE deleted_at IS NULL keeps lookups of live rows fast while the deleted rows pile up in the table.

Variations

  • Generalized partial indexes. Seshadri and Swami (1995) let the system choose the indexed subset from the data and the workload, for example to leave out the most frequent values, whose lookups are better done by a scan.
  • Filtered statistics. SQL Server keeps statistics over the same subset, which helps the optimizer estimate the selectivity of queries on it.
  • Index on an expression. A related tool indexes f(row)f(row) instead of a subset; the two can be combined, as in an index on lower(email) where active.
  • Materialized views with a selection predicate generalize the idea to stored query results, with the same need to prove that a query is contained in the view.
  • Zone maps and bitmap indexes are other ways to skip most of a table for a selective predicate, without a fixed subset.

Pitfalls

  • The optimizer cannot prove the implication. A query with a parameter, status = $1, cannot use an index WHERE status = 0, since the plan must work for every value. A condition written differently, such as status < 1 for status = 0, may also fail, as in the example. Write queries with the same condition as the index.
  • A subset that grows. If the fraction of rows that satisfy PP grows, the index loses its advantage, and if PP is a moving condition such as "created in the last week", it cannot be written with a constant and the index must be rebuilt.
  • Too many partial indexes. One partial index per value of a column (one per status, per tenant) is a full index in pieces, with more overhead and more planning work.
  • Uniqueness only on the subset. A partial unique index does not prevent duplicates outside PP, and a row that changes so that it enters PP can fail on a conflict.
  • Updates that move rows in and out. If rows often enter and leave the subset, every such change is an index insert or delete, and the saving in update cost disappears.

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.

partial_index.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/partial-index/. The authors are listed in prov/5RMQCY.jsonl.

"""A partial index (Stonebraker 1989): an ordered index over only the rows
that satisfy a predicate P, and a planner that uses it only when the query
predicate implies P.

Rows are dicts of integer columns. A predicate is a conjunction of atoms
(column, op, constant) with op in =, <, <=, >, >=. On integer columns each
conjunction is a box: one closed interval per column. Q implies P exactly
when the box of Q lies in the box of P (or the box of Q is empty).
"""

import math
from bisect import bisect_left, bisect_right, insort
from typing import Dict, List, Optional, Sequence, Tuple

Atom = Tuple[str, str, int]
Row = Dict[str, int]
NEG, POS = -math.inf, math.inf


def box(pred: Sequence[Atom]) -> Dict[str, Tuple[float, float]]:
    """The closed interval of each column that the conjunction allows."""
    out: Dict[str, Tuple[float, float]] = {}
    for col, op, c in pred:
        lo, hi = out.get(col, (NEG, POS))
        if op == "=":
            lo, hi = max(lo, c), min(hi, c)
        elif op == "<":
            hi = min(hi, c - 1)
        elif op == "<=":
            hi = min(hi, c)
        elif op == ">":
            lo = max(lo, c + 1)
        elif op == ">=":
            lo = max(lo, c)
        else:
            raise ValueError(op)
        out[col] = (lo, hi)
    return out


def holds(pred: Sequence[Atom], row: Row) -> bool:
    return all(lo <= row[col] <= hi for col, (lo, hi) in box(pred).items())


def implies(q: Sequence[Atom], p: Sequence[Atom]) -> bool:
    """Does every row that satisfies q also satisfy p? Exact for integer boxes."""
    bq, bp = box(q), box(p)
    if any(lo > hi for lo, hi in bq.values()):
        return True                                      # q is never true
    for col, (plo, phi) in bp.items():                   # @line L7
        qlo, qhi = bq.get(col, (NEG, POS))
        if qlo < plo or qhi > phi:                       # @line L7
            return False
    return True                                          # @line L8


class Table:
    def __init__(self, rows: Sequence[Row]):
        self.rows: Dict[int, Row] = {i: dict(r) for i, r in enumerate(rows)}
        self.next_id = len(self.rows)
        self.indexes: List["PartialIndex"] = []
        self.stats = {"scanned": 0, "index_entries": 0, "index_writes": 0}

    def insert(self, row: Row) -> int:
        rid = self.next_id
        self.next_id += 1
        self.rows[rid] = dict(row)
        for ix in self.indexes:
            ix.change(rid, None, self.rows[rid])
        return rid

    def update(self, rid: int, **values) -> None:
        old = dict(self.rows[rid])
        self.rows[rid].update(values)
        for ix in self.indexes:
            ix.change(rid, old, self.rows[rid])

    def delete(self, rid: int) -> None:
        old = self.rows.pop(rid)
        for ix in self.indexes:
            ix.change(rid, old, None)


class PartialIndex:
    """An ordered index on one key column over the rows that satisfy pred."""

    def __init__(self, table: Table, key: str, pred: Sequence[Atom]):
        self.table, self.key, self.pred = table, key, list(pred)
        self.entries: List[Tuple[int, int]] = sorted(               # @line L1
            (r[key], rid) for rid, r in table.rows.items() if holds(self.pred, r))
        table.indexes.append(self)

    def change(self, rid: int, old: Optional[Row], new: Optional[Row]) -> None:
        if old is not None and holds(self.pred, old):               # @line L2
            i = bisect_left(self.entries, (old[self.key], rid))
            del self.entries[i]                                     # @line L2
            self.table.stats["index_writes"] += 1
        if new is not None and holds(self.pred, new):               # @line L3
            insort(self.entries, (new[self.key], rid))              # @line L3
            self.table.stats["index_writes"] += 1


def query(table: Table, key: str, lo: int, hi: int, pred: Sequence[Atom],
          index: Optional[PartialIndex] = None) -> Tuple[List[int], str]:
    """The row ids with lo <= key <= hi and pred, in key order, and the plan used."""
    full = list(pred) + [(key, ">=", lo), (key, "<=", hi)]
    if index is not None and index.key == key and implies(full, index.pred):   # @line L4
        i = bisect_left(index.entries, (lo, -1))
        j = bisect_right(index.entries, (hi, math.inf))
        out = []
        for k, rid in index.entries[i:j]:                            # @line L5
            table.stats["index_entries"] += 1
            if holds(pred, table.rows[rid]):                         # @line L5
                out.append(rid)
        return out, "index"
    out = []
    for rid, r in table.rows.items():                                # @line L6
        table.stats["scanned"] += 1
        if holds(full, r):                                           # @line L6
            out.append(rid)
    out.sort(key=lambda rid: (table.rows[rid][key], rid))
    return out, "scan"
test_partial_index.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/partial-index/. The authors are listed in prov/5RMQCY.jsonl.

import itertools
import random
import unittest

from partial_index import PartialIndex, Table, holds, implies, query

OPS = ["=", "<", "<=", ">", ">="]


def random_pred(rng, cols, n):
    return [(rng.choice(cols), rng.choice(OPS), rng.randrange(0, 6)) for _ in range(n)]


def orders(n, seed):
    rng = random.Random(seed)
    # status 0 = open (about 5%), 1 = shipped
    return [{"cust": rng.randrange(1000), "status": 0 if rng.random() < 0.05 else 1,
             "amount": rng.randrange(1, 500)} for _ in range(n)]


class TestImplication(unittest.TestCase):
    def test_against_brute_force_on_a_grid(self):
        rng = random.Random(1)
        grid = [dict(zip("ab", v)) for v in itertools.product(range(-2, 9), repeat=2)]
        for _ in range(3000):
            q = random_pred(rng, "ab", rng.randrange(0, 4))
            p = random_pred(rng, "ab", rng.randrange(0, 3))
            want = all(holds(p, r) for r in grid if holds(q, r))
            self.assertEqual(implies(q, p), want, (q, p))


class TestExample(unittest.TestCase):
    def test_open_orders(self):
        t = Table(orders(10000, 2))
        ix = PartialIndex(t, "cust", [("status", "=", 0)])
        n_open = sum(1 for r in t.rows.values() if r["status"] == 0)
        self.assertEqual(len(ix.entries), n_open)
        self.assertLess(len(ix.entries), 10000 // 10)
        ref = Table(orders(10000, 2))
        cases = [
            ([("status", "=", 0)], "index"),
            ([("status", "=", 0), ("amount", ">", 100)], "index"),
            ([], "scan"),
            ([("status", "<=", 0)], "scan"),             # status could be negative
            ([("status", "<=", 0), ("status", ">=", 0)], "index"),
            ([("status", "<", 2)], "scan"),
        ]
        for pred, plan in cases:
            got, used = query(t, "cust", 100, 199, pred, ix)
            want, _ = query(ref, "cust", 100, 199, pred)
            self.assertEqual(used, plan)
            self.assertEqual(got, want)


class TestAgainstFullScan(unittest.TestCase):
    def test_random_workload_with_changes(self):
        rng = random.Random(3)
        for seed in range(6):
            rows = [{"k": rng.randrange(50), "a": rng.randrange(6), "b": rng.randrange(6)}
                    for _ in range(300)]
            t, ref = Table(rows), Table(rows)
            p = random_pred(rng, "ab", rng.randrange(1, 3))
            ix = PartialIndex(t, "k", p)
            for step in range(200):
                r = rng.random()
                if r < 0.2:
                    row = {"k": rng.randrange(50), "a": rng.randrange(6), "b": rng.randrange(6)}
                    self.assertEqual(t.insert(row), ref.insert(row))
                elif r < 0.4 and t.rows:
                    rid = rng.choice(sorted(t.rows))
                    v = {rng.choice("kab"): rng.randrange(6)}
                    t.update(rid, **v)
                    ref.update(rid, **v)
                elif r < 0.45 and t.rows:
                    rid = rng.choice(sorted(t.rows))
                    t.delete(rid)
                    ref.delete(rid)
                else:
                    q = random_pred(rng, "ab", rng.randrange(0, 4))
                    lo = rng.randrange(50)
                    hi = lo + rng.randrange(20)
                    got, used = query(t, "k", lo, hi, q, ix)
                    want, _ = query(ref, "k", lo, hi, q)
                    self.assertEqual(got, want)
                    self.assertEqual(used == "index",
                                     implies(q + [("k", ">=", lo), ("k", "<=", hi)], p))
                # the index holds exactly the rows that satisfy p
                self.assertEqual(ix.entries, sorted((r["k"], rid) for rid, r in t.rows.items()
                                                    if holds(p, r)))

    def test_changes_outside_the_predicate_cost_no_index_work(self):
        t = Table(orders(2000, 4))
        PartialIndex(t, "cust", [("status", "=", 0)])
        shipped = [rid for rid, r in t.rows.items() if r["status"] == 1]
        for rid in shipped[:500]:
            t.update(rid, amount=7)
        self.assertEqual(t.stats["index_writes"], 0)
        open_ = [rid for rid, r in t.rows.items() if r["status"] == 0]
        t.update(open_[0], status=1)                 # the row leaves the index
        t.update(shipped[0], status=0)               # and another one enters it
        self.assertEqual(t.stats["index_writes"], 2)


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

Exercises

  1. For an index WHERE a >= 5 AND b < 3, decide which of these queries may use it: a = 7 AND b = 1, a > 4 AND b <= 2, a >= 5, a = 9 AND b < 3 AND c = 0, a > 10 AND a < 8.
  2. Show that the box test of L7 is exact for conjunctions of comparisons on integer columns, and give a predicate with OR for which the test of each disjunct alone is not enough.
  3. A table has NN rows, a fraction ss of which satisfy PP, and each row is updated once to a new key, with no change to the columns of PP. How many index writes does a full index on the key cost, and how many does a partial index cost?

References

  1. Michael Stonebraker, The case for partial indexes, ACM SIGMOD Record 18(4) (1989), pp. 4 to 11, the proposal of indexes over a subset of the rows given by a predicate, and their use by the optimizer
  2. Praveen Seshadri and Arun Swami, Generalized partial indexes, Proceedings of the 11th International Conference on Data Engineering (ICDE 1995), pp. 420 to 427, partial indexes whose predicate is chosen from the data and the query workload

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