Chapter 09

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.

Reading: ~44 min Interactive: 2 widgets Source: Polimi Data Base 2 2025/26 — Lecture 4 (Ranking Queries), slides 1–111 · Fagin, Lotem, Naor — Optimal Aggregation Algorithms for Middleware, PODS 2001

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 NN objects described by dd attributes, and some notion of the “goodness” of an object, find the best kk. It shows up in search engines, e-commerce, recommender systems, and in machine learning as kk-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 kk 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 nn candidates and mm voters, who wins? Two classical answers disagree:

  • Borda (1770): election by order of merit. First place scores 1 point, second 2, …, nn-th scores nn. 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 RR whose total distance to R1,,RnR_1, \ldots, R_n is minimal, for some distance between rankings:

DistanceDefinitionCost of optimizing
Kendall taunumber of exchanges a bubble sort needs to turn one into the otherNP-complete
Spearman’s footrulesum of rank displacements of the same itemPTIME, and approximable

MedRank approximates footrule-optimal aggregation using only positions. It makes sorted accesses one element at a time in each list until kk elements have appeared in more than m/2m/2 lists; those are the top kk, 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 XX is instance-optimal when there is a constant mm — the optimality ratio — such that

Instance optimality

cost(X,I)mcost(Y,I)for every input I and every algorithm Y\mathrm{cost}(X, I) \le m \cdot \mathrm{cost}(Y, I) \quad \text{for every input } I \text{ and every algorithm } Y

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 Θ(logn)\Theta(\log n) against sequential search’s Θ(n)\Theta(n), but on an input whose target sits in the first position, sequential search costs 1 and binary search costs logn\log n. 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 Server

with 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*Miles

Query 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 kk tuples enter the result, and if more than one set of kk 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 kk tuples and stop. If not, and kk is small — the typical case — keep a heap of size kk while scanning: the whole input must be read, at cost O(Nlogk)O(N \log k).

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 0.8Price+0.2Mileage0.8 \cdot Price + 0.2 \cdot Mileage means looking for points close to the ideal target (0,0)(0,0). The set of equally-good points for a value vv satisfies 0.8Price+0.2Mileage=v0.8 \cdot Price + 0.2 \cdot Mileage = v, which rearranges to Mileage=4Price+5vMileage = -4 \cdot Price + 5v: 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 (1000,3)(1000, 3) the target, and “goodness” becomes distance from the target. That reframes a top-k query as a kk-nearest-neighbours query: given a target qq, a relation RR, an integer kk and a distance dd, find the kk tuples closest to qq.

The distances used are the LpL_p (Minkowski) norms:

Minkowski distance

Lp(t,q)=((i=1)mtiqip)1/pL_p(t,q) = \left( \sum_{(i = 1)}^{m} \lvert t_i - q_i \rvert^p \right)^{1 / p}

with three cases doing all the work — and each having a characteristic iso-distance shape:

NormFormulaIso-distance surface
L2L_2itiqi2\sqrt{\sum_i \lvert t_i - q_i \rvert^2} — Euclideancircle / sphere
L1L_1itiqi\sum_i \lvert t_i - q_i \rvert — Manhattanrhombus
LL_\inftymaxitiqi\max_i \lvert t_i - q_i \rvert — Chebyshevsquare

Weights stretch the coordinates, turning circles into ellipsoids, rhombi into rhomboids and squares into rectangles:

Weighted Manhattan distance

L1(t,q;W)=iwidiwheredi=tiqiL_1(t,q;W) = \sum_i w_i \, d_i \quad\text{where}\quad d_i = \lvert t_i - q_i \rvert

Weighted Chebyshev distance
L(t,q;W)=maxiwidiL_\infty(t,q;W) = \max_i \, w_i \, d_i

so the weighted sum you started with is simply a weighted L1L_1 distance. Note that in the weighted L2L_2 the weights are not squared: iwitiqi2\sqrt{\sum_i w_i \lvert t_i - q_i \rvert^2}.

For the middleware setting the model is normalised. Each object oo returned by input list LjL_j has a local score pj(o)[0,1]p_j(o) \in [0,1] where higher is better; the hypercube [0,1]m[0,1]^m is the score space, and the global score is S(o)=S(p1(o),,pm(o))S(o) = S(p_1(o), \ldots, p_m(o)). The common scoring functions:

SSDefinitionReading
SUMp1++pmp_1 + \cdots + p_mweigh all criteria equally
WSUMw1p1++wmpmw_1 p_1 + \cdots + w_m p_mweigh them differently
MINminjpj\min_j p_jjudge by the worst partial score
MAXmaxjpj\max_j p_jjudge by the best partial score

In every case we want the kk 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 kk sorted accesses on each list, buffer what you see, compute the MAX of each object’s available partial scores, and return the best kk. No random accesses, no missing scores needed.

It works because after kk rounds there are at least kk 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 k=1k = 1, 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 SS:

  1. Extract the same number of objects by sorted access in each list, until at least kk objects have been seen in all lists.
  2. For every object seen, complete its score with random accesses wherever needed.
  3. Output the kk objects with the best overall score.

Its complexity is sub-linear, O(N(m1)/mk1/m)O(N^{(m-1)/m} k^{1/m}) — proportional to N\sqrt{N} 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:

  1. Do a sorted access in parallel in each list RiR_i.
  2. For each object oo seen, do random accesses in the other lists to complete its score.
  3. Compute S(o)S(o); if it is among the kk highest so far, keep it in the buffer.
  4. Let sLis_{L_i} be the last score seen under sorted access in RiR_i.
  5. Define the threshold T=S(sL1,,sLm)T = S(s_{L_1}, \ldots, s_{L_m}) — the score of the threshold point τ\tau.
  6. If the kk-th best object’s score is worse than TT, go back to step 1.
  7. Otherwise return the current top kk.

The correctness argument is one sentence: no unseen object can have a partial score above sLis_{L_i} in any list, so by monotonicity none can score above TT; once kk objects beat TT, the answer is fixed.

Cost is measured by the middleware cost model:

Middleware cost

cost=SAcSA+RAcRA\mathrm{cost} = SA \cdot c_{SA} + RA \cdot c_{RA}

with SASA, RARA the numbers of sorted and random accesses and cSAc_{SA}, cRAc_{RA} their unit costs. In the basic setting both are 1. For web sources typically cRA>cSAc_{RA} > c_{SA}, with the limiting case cRA=c_{RA} = \infty — random access impossible, which motivates the next algorithm. A source with no index gives cSA=c_{SA} = \infty.

×

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 oo in list LL 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 S(o)S^-(o) (computed by treating the unknown partial scores as their worst possible values) and an upper bound S+(o)S^+(o) (treating them as the best still possible — the last value seen in each unseen list). The buffer BB is unbounded and kept sorted by decreasing lower bound.

NRA's halting condition

Keep making sorted accesses while S(B[k])<max{  maxi>kS+(B[i]),    S(τ)  }S^-(B[k]) < \max\{\; \max_{i > k} S^+(B[i]), \;\; S(\tau) \;\} That is: stop when the kk-th best lower bound beats both the best upper bound among the objects outside the current top kk, and the threshold point’s score S(τ)S(\tau), which bounds every object not yet seen at all.

NRA is instance-optimal among algorithms making no random accesses, with optimality ratio mm. 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 kk: finding the top-2 can be cheaper than finding the top-1. The lectures’ example needs to reach depth N1N-1 for k=1k=1 but only 3 rounds for k=2k=2.

The four algorithms, side by side — the summary the exam expects you to be able to reconstruct:

AlgorithmScoring functionData accessNotes
B0MAX onlysortedinstance-optimal
FAany monotonesorted + randomcost independent of the scoring function; not instance-optimal
TAany monotonesorted + randominstance-optimal
NRAany monotonesorted onlyinstance-optimal; scores may be uncertain
Q

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.

2025-02-05-q22025Q02Top-k algorithms (FA/TA/NRA)hard12 pts
Dataset D is vertically distributed over three sources with values in [0,1]. Find the top-2 items according to $f(t) = 4\,t.A + 2\,t.B + t.C$. | A | B | C | |---|---|---| | 1: 1.00 | 2: 0.80 | 2: 0.60 | | 7: 0.80 | 1: 0.65 | 7: 0.60 | | 2: 0.70 | 3: 0.55 | 3: 0.50 | | 3: 0.20 | 4: 0.50 | 1: 0.15 | | 6: 0.15 | 5: 0.30 | 5: 0.10 | | 4: 0.10 | 6: 0.30 | 4: 0.00 | | 5: 0.10 | 7: 0.30 | 6: 0.00 | 1. (4 pts) Apply FA. 2. (5 pts) Apply NRA, showing the buffer after each round. 3. (3 pts) Could NRA ever make fewer sorted accesses than FA? Explain. Indicate depth, number of accesses, results, and enough detail to follow each round and the stopping criterion.
Worked exam NRA round by round (exam 2025-02-05)

The setup

Three lists, f=4A+2B+Cf = 4A + 2B + C, k=2k = 2. 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 τ=(1.00,0.80,0.60)\tau = (1.00, 0.80, 0.60), S(τ)=6.20S(\tau) = 6.20. 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. S(τ)=5.10S(\tau) = 5.10. 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. S(τ)=4.40S(\tau) = 4.40.

Stop

The 2nd-best lower bound is 5.00, which beats both the best outside-top-2 upper bound (4.90) and S(τ)=4.40S(\tau) = 4.40. 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, f=4A+2B+Cf = 4A + 2B + C, k=2k = 2 — 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 kk, or swap in the hockey dataset from the February 2026 paper to practise TA with its falling threshold.

Hands-on

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

k = 2
rankABC
11 1.002 0.802 0.60
27 0.801 0.657 0.60
32 0.703 0.553 0.50
43 0.204 0.501 0.15
56 0.155 0.305 0.10
64 0.106 0.304 0.00
75 0.107 0.306 0.00
not started
NRA on the Travel lists, f = 4A + 2B + C, top 2. Press Step to make the first sorted accesses.
Depth
0
Sorted acc.
0
Random acc.
0
Total
0
Try thisLoad Travel with NRA and run to stop — depth 3, 9 sorted, 0 random. Now switch to FA on the same data: depth 4, 12 sorted + 3 random = 15. That gap, and why it opens, is question 3 of the February 2025 paper.
TakeawayAll three read the lists top-down; they differ only in when they dare to stop. FA ignores the scores and waits for k objects to appear in every list; TA lets the threshold fall until the k-th score overtakes it; NRA never probes by id, trading a few exact scores for the right answer with the fewest accesses.

09 · Caveat

When the scoring function is not monotone

Every guarantee above — FA’s correctness, TA’s stopping rule, NRA’s bounds — assumes SS 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

f(x,y)=m+s,m=x+y2,s=(xm)2+(ym)2f(x,y) = m + s, \qquad m = \tfrac{x+y}{2}, \qquad s = \sqrt{(x-m)^2 + (y-m)^2}

— the mean travel time plus a penalty for imbalance, ss being the distance from the bisector x=yx = y. Lower is better. It is not monotone: increasing one coordinate can reduce ff 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 ff 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 erp=100MYCT+10MMIN+MMAX+CACHerp = -100\,MYCT + 10\,MMIN + MMAX + CACH, 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 L1L_1 distances; iso-score lines are parallel and weights rotate them.
  • The four algorithms. B0 — MAX only, kk sorted accesses per list. FA — any monotone SS, stop when kk objects are seen in all lists, then complete by random access; not instance-optimal. TA — stop when the kk-th score beats the threshold S(τ)S(\tau) built from the last seen sorted values; instance-optimal. NRA — sorted only, lower/upper bounds, uncertain scores, cost not monotone in kk.
  • 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.