Data

Quota queries

Building on the basic relational operations, we have the ability to perform quota queries. An example of a quota query is "find the three heaviest parts".

Quota

The quota operator takes a relational expression, an ordered set of attributes and a quota count. Each attribute name in the ordered set can be prefixed with - to use a descending order, otherwise an ascending order is used.

Again, given the example parts relvar:

P
PNOPNAMECOLORWEIGHTCITY
P1NutRed12London
P2BoltGreen17Paris
P3ScrewBlue17Rome
P4ScrewRed14London
P5CamBlue12Paris
P6CogRed19London

We can get the three heaviest parts using the quota operator.

For example:

quota(P, {-WEIGHT}, 3)
PNOPNAMECOLORWEIGHTCITY
P2BoltGreen17Paris
P3ScrewBlue17Rome
P6CogRed19London

Note:

Another example to find the part(s) with the smallest weight:

quota(P, {WEIGHT}, 1)
PNOPNAMECOLORWEIGHTCITY
P1NutRed12London
P5CamBlue12Paris

Notice we get two tuples because they share the smallest weight. We can break the tie here if we want by adding another attribute to the ordering, e.g. -PNO to mean: if there's a tie choose the part with the largest PNO:

quota(P, {WEIGHT, -PNO}, 1)
PNOPNAMECOLORWEIGHTCITY
P5CamBlue12Paris

Another example, to "get all suppliers whose status is one of the two smallest":

quota(S{STATUS}, {STATUS}, 2) & S
STATUSSNOSNAMECITY
10S2JonesParis
20S1SmithLondon
20S4ClarkLondon

Shorthand

Note: the quota operator is just a shorthand for something like this:

P{*, heavier:=count(P{*, WT:=WEIGHT}[WT > WEIGHT])}[heavier < 3]~{heavier}