Ranking Queries & Top-k Algorithms
Finding the best k objects when "best" is a scoring function over several criteria. Rank aggregation and instance optimality, the geometry of weighted scores, and the four middleware algorithms — B0, FA, TA and NRA — with the stopping rule and access count each one is graded on.
01 · Motivation
Why “best” needs a definition
In business applications a query has an exact result and every row is equally relevant. In consumer applications there is a notion of preferability — and preferences over several criteria at once rarely agree.
The general problem: given objects described by attributes, and some notion of the “goodness” of an object, find the best . It shows up in search engines, e-commerce, recommender systems, and in machine learning as -nearest-neighbours, feature selection and classification.
Two families of answer, and this chapter and the next take one each:
Ranking (top-k) queries
Define a scoring function that collapses the criteria into one number, and return the top objects by that score. You control the result size exactly; you must supply the weights.
Skyline queries
Return the set of non-dominated objects — those nothing else beats on every criterion. No weights needed; no control over how many come back. Chapter 10.
02 · Foundations
Rank aggregation
The oldest version of the problem, from social choice theory: combine several ranked lists into one consensus ranking, when no scores are visible — only positions.
Given candidates and voters, who wins? Two classical answers disagree:
- Borda (1770): election by order of merit. First place scores 1 point, second 2, …, -th scores . A candidate’s penalty is the sum; the Borda winner has the lowest penalty.
- Condorcet (1785): the Condorcet winner is the candidate who defeats every other in a pairwise majority contest.
They can pick different winners on the same ballots — the lectures’ example gives Borda to C (penalty 16) while A wins every pairwise contest. Worse, Condorcet’s paradox: with cyclic preferences (voter 1 ranks C B A, voter 2 ranks B A C, voter 3 ranks A C B) no Condorcet winner exists.
The metric approach instead seeks a new ranking whose total distance to is minimal, for some distance between rankings:
| Distance | Definition | Cost of optimizing |
|---|---|---|
| Kendall tau | number of exchanges a bubble sort needs to turn one into the other | NP-complete |
| Spearman’s footrule | sum of rank displacements of the same item | PTIME, and approximable |
MedRank approximates footrule-optimal aggregation using only positions. It makes sorted accesses one element at a time in each list until elements have appeared in more than lists; those are the top , ordered by median rank. The maximum number of sorted accesses per list is the algorithm’s depth. In the hotels example, at depth 5 the answer is Novotel (median 3), then Hilton and Ibis (median 5 each).
03 · Theory
Instance optimality
The guarantee that makes some of these algorithms remarkable, and it is considerably stronger than worst-case optimality.
An algorithm is instance-optimal when there is a constant — the optimality ratio — such that
The quantifier order is what matters: for every input, not on average and not in the worst case. A worst-case-optimal algorithm may still be beaten arbitrarily badly on particular inputs. Binary search is the standard illustration — it is worst-case optimal at against sequential search’s , but on an input whose target sits in the first position, sequential search costs 1 and binary search costs . So binary search is not instance-optimal.
MedRank is not optimal in the absolute sense, but it is instance-optimal among algorithms that access the lists in sorted order, with optimality ratio 2.
04 · SQL
Top-k queries in SQL
Two capabilities are needed — order by score, and stop after k. SQL took until 2008 to standardise the second.
SELECT * FROM USEDCARS
WHERE Vehicle = 'Audi/A4'
ORDER BY 0.8 * Price + 0.2 * Miles
FETCH FIRST 5 ROWS ONLY; -- SQL:2008; DB2, PostgreSQL, Oracle, SQL Serverwith the non-standard spellings still common in the wild: LIMIT k (PostgreSQL, MySQL),
ROWNUM <= k (Oracle), SELECT TOP k (SQL Server).
The weights 0.8 and 0.2 are how you say that price matters four times as much as mileage. Their
necessity is the point of the following comparison:
-- A: hard threshold -- B: rank everything
WHERE Vehicle='Audi/A4' WHERE Vehicle='Audi/A4'
AND Price <= 21000 ORDER BY 0.8*Price + 0.2*Miles
ORDER BY 0.8*Price + 0.2*MilesQuery A suffers near-miss: a car at €21 500 with exceptionally low mileage is discarded although it may be the best deal. Query B suffers information overload: every Audi A4 in the database comes back. Top-k is the middle path.
Ties make top-k non-deterministic
Only the first tuples enter the result, and if more than one set of satisfies the
ORDER BY, any of them is a valid answer. With prices 30, 30, 40, 40
and
FETCH FIRST 3, both {30, 30, 40} choices are correct. Exam solutions say so
explicitly — “any two among A, B, D, G, chosen non-deterministically” — and the January 2024
grader’s note adds a corollary:
if two objects tie for first, the next rank is 3, not 2.
Evaluation depends on the access paths available. For a single relation: if the input is already sorted by the scoring function, read the first tuples and stop. If not, and is small — the typical case — keep a heap of size while scanning: the whole input must be read, at cost .
05 · Model
Geometry: distances, weights, and the score space
Seeing scores geometrically explains what weights do, and connects top-k to nearest-neighbour search.
Represent each tuple as a point — say (Price, Mileage). Minimising means looking for points close to the ideal target . The set of equally-good points
for a value satisfies , which rearranges to
: a family of parallel lines of slope −4. Changing the weights
rotates the family, and a different point touches it first — which is exactly how weights select a
winner.
The target need not be the origin. Looking for a house with a 1000 m² garden and 3 bedrooms makes the target, and “goodness” becomes distance from the target. That reframes a top-k query as a -nearest-neighbours query: given a target , a relation , an integer and a distance , find the tuples closest to .
The distances used are the (Minkowski) norms:
with three cases doing all the work — and each having a characteristic iso-distance shape:
| Norm | Formula | Iso-distance surface |
|---|---|---|
| — Euclidean | circle / sphere | |
| — Manhattan | rhombus | |
| — Chebyshev | square |
Weights stretch the coordinates, turning circles into ellipsoids, rhombi into rhomboids and squares into rectangles:
so the weighted sum you started with is simply a weighted distance. Note that in the weighted the weights are not squared: .
For the middleware setting the model is normalised. Each object returned by input list has a local score where higher is better; the hypercube is the score space, and the global score is . The common scoring functions:
| Definition | Reading | |
|---|---|---|
SUM | weigh all criteria equally | |
WSUM | weigh them differently | |
MIN | judge by the worst partial score | |
MAX | judge by the best partial score |
In every case we want the objects with the highest global score — even for MIN.
06 · Algorithms
B0 and Fagin’s Algorithm
The middleware setting: the data is vertically distributed, each source can be read in descending score order (sorted access) or probed by object id ( random access), and we want the top k without reading everything.
The simplest case is MAX, and Fagin’s 1996 answer is almost embarrassing:
B0 — for MAX only
Make sorted accesses on each list, buffer what you see, compute the MAX of each object’s available partial scores, and return the best . No random accesses, no missing scores needed.
It works because after rounds there are at least objects whose score is at least the last
value seen; any object not yet retrieved has every partial score below that, so its MAX is too. The
same argument collapses for any other function — with MIN and , the sorted phase gives no
lower bound at all on the retrieved objects’ global scores, so an unseen object can still win. Even
completing the seen objects with random accesses does not fix it.
Fagin’s Algorithm (FA) handles any monotone :
- Extract the same number of objects by sorted access in each list, until at least objects have been seen in all lists.
- For every object seen, complete its score with random accesses wherever needed.
- Output the objects with the best overall score.
Its complexity is sub-linear, — proportional to for two lists. But note the shape of the stopping rule: it counts objects in common, so it is independent of the scoring function. That is FA’s weakness — it cannot adapt to how the function actually behaves — and it is why FA is not instance-optimal. It must also buffer every object seen under sorted access.
FA stops on objects common to ALL lists
The January 2024 grader’s note is explicit:
“FA can stop when k=2 objects in common are found in ALL lists. Stopping when 2 objects in common are found in just 2 lists is wrong.”
With three lists, an object seen in two of them does not count.
07 · Algorithms
The Threshold Algorithm
Change the stopping condition so that it depends on the scoring function, and you get an algorithm that is instance-optimal — work its authors received the Gödel Prize for in 2014.
TA interleaves the two access types:
- Do a sorted access in parallel in each list .
- For each object seen, do random accesses in the other lists to complete its score.
- Compute ; if it is among the highest so far, keep it in the buffer.
- Let be the last score seen under sorted access in .
- Define the threshold — the score of the threshold point .
- If the -th best object’s score is worse than , go back to step 1.
- Otherwise return the current top .
The correctness argument is one sentence: no unseen object can have a partial score above in any list, so by monotonicity none can score above ; once objects beat , the answer is fixed.
Cost is measured by the middleware cost model:
with , the numbers of sorted and random accesses and , their unit costs. In the basic setting both are 1. For web sources typically , with the limiting case — random access impossible, which motivates the next algorithm. A source with no index gives .
Counting accesses — three rules the graders enforce
A row costs one sorted access per list. Descending one level across three lists is 3 sorted accesses, not 1.
You still pay the sorted access even if you already knew the score. You cannot know in advance which object a sorted access will return, so “saving” it is wrong.
But you must not re-fetch a score you already have. No random access for object in list if a previous sorted or random access already revealed it. Both orderings of the work — all sorted accesses of a row then the needed random ones, or one sorted access followed immediately by its random ones — are acceptable, and they can give slightly different random-access counts.
08 · Algorithms
NRA — when random access is impossible
Some sources cannot be probed by id at all. NRA returns the right top k using sorted access only — at the price of not always knowing the winners’ exact scores.
The idea is to maintain, for every object seen, a lower bound (computed by treating the unknown partial scores as their worst possible values) and an upper bound (treating them as the best still possible — the last value seen in each unseen list). The buffer is unbounded and kept sorted by decreasing lower bound.
NRA's halting condition
Keep making sorted accesses while That is: stop when the -th best lower bound beats both the best upper bound among the objects outside the current top , and the threshold point’s score , which bounds every object not yet seen at all.
NRA is instance-optimal among algorithms making no random accesses, with optimality ratio . Two properties surprise people:
- The returned objects are correct, but their scores may remain uncertain — a lower bound below an upper bound. That is by design.
- Cost is not monotone in : finding the top-2 can be cheaper than finding the top-1. The lectures’ example needs to reach depth for but only 3 rounds for .
The four algorithms, side by side — the summary the exam expects you to be able to reconstruct:
| Algorithm | Scoring function | Data access | Notes |
|---|---|---|---|
| B0 | MAX only | sorted | instance-optimal |
| FA | any monotone | sorted + random | cost independent of the scoring function; not instance-optimal |
| TA | any monotone | sorted + random | instance-optimal |
| NRA | any monotone | sorted only | instance-optimal; scores may be uncertain |
Top-k algorithms — 5 of 14 sessions, 56 points
Ranking exercises appear in 5 of the 14 papers (2024-01-24, 2024-06-17, 2025-02-05, 2025-07-02, 2026-02-13), and the ask is always mechanical execution:
indicate the depth, the number of sorted and random accesses, the buffer at each round, and the stopping criterion
. Several papers set two algorithms on the same data to force a comparison — FA against TA in January 2024, FA against NRA in February 2025 — and then ask which was cheaper on this instance and why.
The setup
Three lists, , . List A: 1:1.00, 7:0.80, 2:0.70, 3:0.20, … List B: 2:0.80, 1:0.65, 3:0.55, 4:0.50, … List C: 2:0.60, 7:0.60, 3:0.50, 1:0.15, …
Round 1 — 3 sorted accesses
Seen: item 1 (A = 1.00), item 2 (B = 0.80, C = 0.60). Bounds — item 1: lb 4.00, ub 6.20; item 2: lb 2.20, ub 6.20. Threshold point , . The 2nd-best lower bound (2.20) loses to 6.20 — continue.
Round 2 — 3 more
Item 1 gains B = 0.65 → lb 5.30, ub 5.90. Item 7 appears (A = 0.80, C = 0.60) → lb 3.80, ub 5.10. Item 2’s ub falls to 5.40. . 2nd-best lb is 1.40 — still losing. Continue.
Round 3 — item 2 completes
Item 2 now has all three scores (0.70, 0.80, 0.60) → lb = ub = 5.00. Item 1: lb 5.30, ub 5.80. Item 7: ub 4.90. Item 3 enters with ub 4.40. .
Stop
The 2nd-best lower bound is 5.00, which beats both the best outside-top-2 upper bound (4.90) and . Halt. Depth 3, 9 sorted accesses, 0 random. Top-2 = items 1 and 2 — with item 1’s exact score still uncertain in [5.30, 5.80].
Why it beat FA here
FA needed depth 4 (12 sorted + 3 random = 15 accesses) because its stopping rule ignores the scoring function. NRA’s rule uses it, so it halted a level earlier. The price is exactly that residual uncertainty on item 1’s score.
Now run it yourself. The stepper opens on exactly this scenario — the same three lists, , — so you can replay the trace above one round at a time. Then switch the algorithm to FA to watch the extra accesses pile up, change , or swap in the hockey dataset from the February 2026 paper to practise TA with its falling threshold.
Top-k stepper — FA · TA · NRA
Pick a past-paper dataset, an algorithm and a k, then step one round of sorted access at a time. Watch the buffer fill, the threshold (or the lower/upper bounds) move, and the stop test flip — the numbers are the ones the official solutions print, so you can mark your own working. Switch algorithm on the same data to see which halts first, and at what cost.
f = 4A + 2B + C · 3 sorted lists · from 2025-02-05 · Exercise B
| rank | A | B | C |
|---|---|---|---|
| 1 | 1 1.00 | 2 0.80 | 2 0.60 |
| 2 | 7 0.80 | 1 0.65 | 7 0.60 |
| 3 | 2 0.70 | 3 0.55 | 3 0.50 |
| 4 | 3 0.20 | 4 0.50 | 1 0.15 |
| 5 | 6 0.15 | 5 0.30 | 5 0.10 |
| 6 | 4 0.10 | 6 0.30 | 4 0.00 |
| 7 | 5 0.10 | 7 0.30 | 6 0.00 |
09 · Caveat
When the scoring function is not monotone
Every guarantee above — FA’s correctness, TA’s stopping rule, NRA’s bounds — assumes is monotone. One paper builds an entire exercise on removing that assumption.
June 2024 asks for a meeting point between Milan and Como, scored by
— the mean travel time plus a penalty for imbalance, being the distance from the bisector . Lower is better. It is not monotone: increasing one coordinate can reduce by making the pair more balanced.
What happens is instructive:
- TA runs to depth 3 and returns C, which is not in the skyline. That is legal — the skyline is the set of top-1 candidates for monotone functions, and is not one.
- FA stops at depth 2, having seen only A and B in both lists, and returns one of them. This answer is simply wrong: the unseen C beats both. FA’s correctness proof needs monotonicity, and without it an unseen object can outscore every fully-seen one.
A second paper, July 2025, plays the opposite trick: the CPU dataset scores
, with a negative coefficient. Here TA does apply —
because MYCT is listed in ascending order, so descending that list still decreases utility, exactly
as for the other three. Monotonicity in the access order is what the algorithms need, not positive
coefficients.
TA is instance-optimal. On a particular dataset with scoring function MAX, could another algorithm from the course beat it in total accesses?
Load-bearing ideas
- Two answers to multi-criteria “best”: a scoring function (this chapter, exact result size, you supply weights) or dominance (chapter 10, no weights, uncontrolled size).
- Rank aggregation — Borda sums positions, Condorcet wins pairwise contests, and they disagree; Condorcet winners may not exist. Kendall tau is NP-complete to optimize, Spearman’s footrule is not, and MedRank approximates it from positions alone.
- Instance optimality — within a constant factor of any algorithm on every input. Far stronger than worst-case optimality, which binary search has and instance optimality it does not.
- Weighted sums are weighted distances; iso-score lines are parallel and weights rotate them.
- The four algorithms. B0 — MAX only, sorted accesses per list. FA — any monotone , stop when objects are seen in all lists, then complete by random access; not instance-optimal. TA — stop when the -th score beats the threshold built from the last seen sorted values; instance-optimal. NRA — sorted only, lower/upper bounds, uncertain scores, cost not monotone in .
- Counting rules: one sorted access per list per row; never skip a sorted access; never repeat a random access for a score you already have.
- Everything assumes monotonicity. Without it TA may return a non-skyline point (legal) and FA may return the wrong answer (not legal). Monotone in the access order is what matters — a negative coefficient is fine if its list is sorted accordingly.
- Exam radar. Re-derive before the exam: a full TA round-by-round trace with threshold and buffer; the NRA halting condition with both maxima; and the sentence that distinguishes FA’s stopping rule from TA’s.