Aggregates
An aggregate computes one value from several rows: a count, a sum, an
average, a minimum, a maximum. Django has two methods for them,
annotate() (a value per row) and aggregate() (a value for the whole
queryset), and a third form, values().annotate(), for groups. rind has
the same three, and this page takes each one in turn:
| You want | Django | rind | Section |
|---|---|---|---|
| for each train, the number of its wagons | Train.objects.annotate(n=Count("wagons")) | Train::wagons().count() | Per row |
| the number of wagons of all trains | Wagon.objects.aggregate(n=Count("id")) | func::count() | Over the whole query |
| for each journey, the number of its reservations, from the reservations | Reservation.objects.values("journey").annotate(n=Count("id")) | group_by(…) | Grouped queries |
The data used below: train 1 (Atlantique) has three wagons of 4, 2 and 2
places (two seats, one sleeper); train 2 (Armor Fret) two freight
wagons of 1000 and 500 kg; train 3 (Cornouaille) one seats wagon of 50.
Per row, over a relation
To compute, for each row of the query, a value over the rows of one of its many relations, start from the relation:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
let wagons = || Train::wagons().rows();
let seated = || Train::wagons().filter(|w| w.kind().ne("freight"));
let select = Query::<Train>::new()
.select((
Train::id(),
wagons().count(),
wagons().sum(|w| w.capacity()),
seated().count(),
seated().max(|w| w.capacity()),
))
.order_by([Train::id().asc()])
.into_select();
let rows: Vec<(i64, i64, Option<i64>, i64, Option<i32>)> = db.rows(&select).await?;
}
SELECT "t0"."id",
(SELECT COUNT(*) FROM "fleet_wagon" AS "t1" WHERE "t1"."train_id" = "t0"."id"),
CAST((SELECT SUM("t1"."capacity") FROM "fleet_wagon" AS "t1" WHERE "t1"."train_id" = "t0"."id") AS bigint),
(SELECT COUNT(*) FROM "fleet_wagon" AS "t1" WHERE "t1"."train_id" = "t0"."id" AND "t1"."kind" <> $1),
(SELECT MAX("t1"."capacity") FROM "fleet_wagon" AS "t1" WHERE "t1"."train_id" = "t0"."id" AND "t1"."kind" <> $2)
FROM "fleet_train" AS "t0"
ORDER BY "t0"."id"
-- params: [Text("freight"), Text("freight")]
[(1, 3, Some(8), 3, Some(4)),
(2, 2, Some(1500), 0, None),
(3, 1, Some(50), 1, Some(50))]
Read it piece by piece.
Which rows: rows() and filter
Train::wagons() is the relation. Two methods say which of its rows the
aggregate is over:
.rows(): every related row..filter(|w| …): only the related rows that match, as Django’sCount("wagons", filter=Q(…))does. Severalfiltercalls combine with and.
#![allow(unused)]
fn main() {
Train::wagons().rows() // every wagon of the train
Train::wagons().filter(|w| w.kind().ne("freight")) // its passenger wagons
Train::wagons().filter(|w| w.kind().eq("seats")).filter(|w| w.capacity().ge(4))
}
count() has a shortcut: Train::wagons().count() is
Train::wagons().rows().count(). The other aggregates need rows() or
filter first.
Which value: the aggregates
| Method | SQL | Read as | With no rows |
|---|---|---|---|
count() | COUNT(*) | i64 | 0 |
sum(|w| w.col()) | SUM(col), cast to bigint for integers | Option<i64> (integers), Option<f64> (floats) | None |
avg(|w| w.col()) | AVG(col) | Option<f64> | None |
min(|w| w.col()), max(…) | MIN(col), MAX(col) | Option<T>, T the column’s type | None |
std_dev(|w| w.col()) | STDDEV_POP(col) | Option<f64> | None |
std_dev_sample(|w| w.col()) | STDDEV_SAMP(col) | Option<f64> | None, also with one row |
The closure receives a path to the related row and returns the column to aggregate.
Every aggregate but count is NULL when there are no rows, as in
SQL: train 2 has no passenger wagon, so its max is None, while its
count is 0. Read them as Option, or wrap them in
func::coalesce.
The types of the results: a sum of integers is always a bigint
(rind casts it), so it is read as an i64 even for an integer column. A
minimum and a maximum keep the column’s SQL type: capacity is an
integer, so max is read as an i32.
The averages and deviations of the sample’s trains:
#![allow(unused)]
fn main() {
(Train::id(), wagons().avg(|w| w.capacity()), wagons().min(|w| w.capacity()))
// [(1, Some(2.6666666666666665), Some(2)), (2, Some(750.0), Some(500)), (3, Some(50.0), Some(50))]
(Train::id(), wagons().std_dev(|w| w.capacity()), wagons().std_dev_sample(|w| w.capacity()))
// [(1, Some(0.94…), Some(1.15…)), (2, Some(250.0), Some(353.55…)), (3, Some(0.0), None)]
}
Aggregates as filters and orders
An aggregate is an expression: it filters and orders like a column.
#![allow(unused)]
fn main() {
// The stations at least two journeys leave from.
Query::<Station>::new().filter(Station::departures().count().ge(2))
// WHERE (SELECT COUNT(*) FROM "timetable_journey" AS "t1" WHERE "t1"."origin_id" = "t0"."id") >= $1
// → station 1
// The stations from which no planned journey leaves.
Query::<Station>::new()
.filter(Station::departures().filter(|j| j.status().eq("planned")).count().eq(0))
// → stations 3, 4, 5, 6
// The trains whose wagons hold more than 100 times their id (an aggregate against an expression).
Query::<Train>::new().filter(Train::wagons().rows().sum(|w| w.capacity()).gt(Train::id() * 100))
// WHERE CAST((SELECT SUM("t1"."capacity") …) AS bigint) > ("t0"."id" * $1) → train 2
// The stations, the busiest first.
Query::<Station>::new()
.order_by([Station::departures().count().desc(), Station::id().asc()])
}
In Django, filtering on an aggregate needs annotate() then filter()
on the annotation’s name. In rind the expression goes straight into the
filter.
Through other relations
The relation can be reached through foreign keys: the number of wagons of each journey’s train:
#![allow(unused)]
fn main() {
Query::<Journey>::new().select((Journey::code(), Journey::train().wagons().count()))
}
SELECT "t0"."code", (SELECT COUNT(*) FROM "fleet_wagon" AS "t1" WHERE "t1"."train_id" = "train"."id")
FROM "timetable_journey" AS "t0"
INNER JOIN "fleet_train" AS "train" ON "train"."id" = "t0"."train_id"
-- → [("J100", 3), ("J200", 2), ("J300", 3), ("J400", 1)]
and a many-to-many relation is aggregated like the others, through its link table:
#![allow(unused)]
fn main() {
Query::<User>::new().select((User::username(), User::groups().count()))
// → [("root", 0), ("sam", 0), ("alice", 1), ("bob", 2), ("carol", 0)]
}
Several aggregates do not multiply each other
In Django, two aggregates over two different relations of the same
queryset join both relations, and each count is multiplied by the
other’s rows (the famous “Count with two joins” bug, which
distinct=True only partly fixes). In rind, each aggregate is computed on
its own: wagons().count() and journeys().count() side by side are both
right.
In serializers
The same expressions give the values a serializer computes for a page:
#![allow(unused)]
fn main() {
#[annotated(expr = Train::wagons().count(), on_request)]
pub wagons_count: Option<i64>,
#[annotated(
expr = Train::wagons().filter(|w| w.kind().ne("freight")).sum(|w| w.capacity()),
on_request
)]
pub seats: Option<Option<i64>>,
}
Per row, or for every row at once: grouped()
By default, each aggregate is a correlated sub-query: for each row the
query reads, PostgreSQL runs SELECT COUNT(*) … WHERE train_id = <this train>. This is the right choice when the query reads few rows (a page,
a filtered list) and an index serves each sub-query: the foreign key’s
index does.
When the aggregate is needed for most rows of a large table (a filter
or an order on it, over the whole table), running a sub-query per row is
slow. Add .grouped() to the relation: the aggregate is then computed
once, for every train, by one grouped query joined to the main one:
#![allow(unused)]
fn main() {
// sample/tests/db.rs
let wagons = || Train::wagons().rows().grouped();
let select = Query::<Train>::new()
.filter(wagons().count().ge(2))
.select((Train::id(), wagons().count(), wagons().sum(|w| w.capacity())))
.order_by([wagons().sum(|w| w.capacity()).desc()])
.into_select();
}
SELECT "t0"."id", COALESCE("wagons_g0"."v0", 0), CAST("wagons_g0"."v1" AS bigint)
FROM "fleet_train" AS "t0"
LEFT JOIN (SELECT "t0"."train_id" AS "k", COUNT(*) AS "v0", SUM("t0"."capacity") AS "v1"
FROM "fleet_wagon" AS "t0"
GROUP BY "t0"."train_id") AS "wagons_g0" ON "wagons_g0"."k" = "t0"."id"
WHERE COALESCE("wagons_g0"."v0", 0) >= $1
ORDER BY CAST("wagons_g0"."v1" AS bigint) DESC
-- params: [Int(2)]
-- → [(2, 2, Some(1500)), (1, 3, Some(8))]
- The result is the same as without
grouped(). - The aggregates of one grouped relation (here
countandsum) are computed in the same pass: oneGROUP BYfor all of them. - A
countstays0for a train without wagons (COALESCE(…, 0)): theLEFT JOINkeeps it. - A filter on the relation goes inside the grouped query:
#![allow(unused)]
fn main() {
let seats = || Train::wagons().filter(|w| w.kind().eq("seats")).grouped();
Query::<Train>::new().select((Train::id(), seats().count()))
// LEFT JOIN (SELECT "t0"."train_id" AS "k", COUNT(*) AS "v0" FROM "fleet_wagon" AS "t0"
// WHERE "t0"."kind" = $1 GROUP BY "t0"."train_id") AS "wagons_g0" …
// → [(1, 2), (2, 0), (3, 1)]
}
grouped() works on a many relation reached from the model queried,
directly or through foreign keys, and on many-to-many relations:
#![allow(unused)]
fn main() {
Query::<User>::new().select((User::username(), User::groups().rows().grouped().count()))
// LEFT JOIN (SELECT "groups_through"."user_id" AS "k", COUNT(*) AS "v0"
// FROM "accounts_group" AS "t0"
// INNER JOIN "accounts_user_groups" AS "groups_through" ON "groups_through"."group_id" = "t0"."id"
// GROUP BY "groups_through"."user_id") AS "groups_g0" ON "groups_g0"."k" = "t0"."id"
}
Which one to choose? Start without grouped(). Add it when a list
filtered or ordered on an aggregate is slow on real data, and check with
EXPLAIN ANALYZE that it helps: on a page of 20 rows, the sub-queries are
usually faster; over 100,000 rows, the grouped query is.
Over the whole query
Without a relation, the functions of rind::query::func aggregate the
rows of the query itself. This is Django’s aggregate():
#![allow(unused)]
fn main() {
use rind::query::func;
let select = Query::<Wagon>::new()
.filter(Wagon::kind().ne("freight"))
.select((
func::count(),
func::sum(Wagon::capacity()),
func::avg(Wagon::capacity()),
func::min(Wagon::capacity()),
func::max(Wagon::capacity()),
))
.into_select();
let rows: Vec<(i64, Option<i64>, Option<f64>, Option<i32>, Option<i32>)> = db.rows(&select).await?;
let (count, sum, avg, min, max) = rows[0];
}
SELECT COUNT(*), CAST(SUM("t0"."capacity") AS bigint), CAST(AVG("t0"."capacity") AS double precision),
MIN("t0"."capacity"), MAX("t0"."capacity")
FROM "fleet_wagon" AS "t0"
WHERE "t0"."kind" <> $1
-- → [(4, Some(58), Some(14.5), Some(2), Some(50))]
The answer is always one row, even when no row matches:
#![allow(unused)]
fn main() {
Query::<Wagon>::new()
.filter(Wagon::kind().eq("nothing"))
.select((func::count(), func::sum(Wagon::capacity())))
// → [(0, None)]
}
| Function | SQL | Read as |
|---|---|---|
func::count() | COUNT(*) | i64 |
func::sum(x) | SUM(x), cast to bigint for integers | Option<i64>, Option<f64> |
func::avg(x) | AVG(x), cast to double precision | Option<f64> |
func::min(x), func::max(x) | MIN(x), MAX(x) | Option<T> |
func::std_dev(x) | STDDEV_POP(x) | Option<f64> |
x is a path or an expression: func::sum(Wagon::capacity() * 2).
For a count alone, db.count(&query) is shorter.
Grouped queries: group_by and having
A grouped query gives one row per group of rows: the reservations of each
journey, the wagons of each kind. It is written as in SQL, with
group_by and having. This is Django’s values(…).annotate(…):
#![allow(unused)]
fn main() {
// sample/tests/db.rs
// The journeys with at least two booked reservations, and how many.
let per_journey = Query::<Reservation>::new()
.filter(Reservation::status().eq("booked"))
.group_by(Reservation::journey_id())
.having(func::count().ge(2))
.select((Reservation::journey_id(), func::count()));
let rows: Vec<(i64, i64)> = db.rows(&per_journey.clone().into_select()).await?;
let groups: i64 = db.count(&per_journey).await?;
}
SELECT "t0"."journey_id", COUNT(*)
FROM "booking_reservation" AS "t0"
WHERE "t0"."status" = $1
GROUP BY "t0"."journey_id"
HAVING COUNT(*) >= $2
-- params: [Text("booked"), Int(2)]
-- → rows [(1, 3)], groups 1
filterkeeps rows before they are grouped (SQL’sWHERE).group_bytakes a path, or a tuple of paths: one group per combination of values.havingkeeps groups after they are aggregated, with a condition on an aggregate (SQL’sHAVING). Django writes it as afilter()afterannotate().selectsays what each group gives: the keys and the aggregates. Selecting a column that is not a key nor in an aggregate is refused by PostgreSQL.db.countof a grouped query counts the groups:
SELECT COUNT(*)
FROM (SELECT 1 FROM "booking_reservation" AS "t0" WHERE "t0"."status" = $1
GROUP BY "t0"."journey_id" HAVING COUNT(*) >= $2) AS "counted"
Grouping by several keys
#![allow(unused)]
fn main() {
Query::<Reservation>::new()
.group_by((Reservation::journey_id(), Reservation::status()))
.select((Reservation::journey_id(), Reservation::status(), func::count()))
.order_by([Reservation::journey_id().asc(), Reservation::status().asc()])
// GROUP BY "t0"."journey_id", "t0"."status"
// → [(1, "booked", 3), (1, "cancelled", 1), (2, "booked", 1)]
}
Grouping through a relation
The keys can be columns of related rows, joined as in a filter:
#![allow(unused)]
fn main() {
// Reservations per train, the busiest first.
Query::<Reservation>::new()
.group_by(Reservation::wagon().train_id())
.select((Reservation::wagon().train_id(), func::count()))
.order_by([func::count().desc()])
}
SELECT "wagon"."train_id" AS "wagon__train_id", COUNT(*)
FROM "booking_reservation" AS "t0"
INNER JOIN "fleet_wagon" AS "wagon" ON "wagon"."id" = "t0"."wagon_id"
GROUP BY "wagon"."train_id"
ORDER BY COUNT(*) DESC
-- → [(1, 4), (2, 1)]
An aggregate orders the groups, as here.
Collecting the values of a group: array_agg
On a path to an integer column, .array_agg() collects the values of the
group into an array, sorted:
#![allow(unused)]
fn main() {
Query::<Reservation>::new()
.group_by(Reservation::journey().code())
.select((Reservation::journey().code(), func::count(), Reservation::wagon_id().array_agg()))
.order_by([Reservation::journey().code().asc()])
}
SELECT "journey"."code" AS "journey__code", COUNT(*), ARRAY_AGG("t0"."wagon_id" ORDER BY "t0"."wagon_id")
…
GROUP BY "journey"."code"
-- → [("J100", 4, [1, 1, 2, 3]), ("J200", 1, [4])]
It is read as a Vec<i64>. This is django.contrib.postgres’
ArrayAgg, for integer columns only.
Choosing the form
| Question | Form |
|---|---|
| “For each train, how many wagons?” (one row per train, trains without wagons included) | per row: Train::wagons().count() |
| “Which trains have more than two wagons?” | per row, in a filter: .filter(Train::wagons().count().gt(2)) |
| “Over every train, sorted by their wagons” on a large table | per row, grouped() |
| “How many wagons in total?” | whole query: func::count(), or db.count |
| “How many reservations per status?” (one row per value) | group_by |
The per-row form starts from the model you want rows of, and keeps every row of it. A grouped query starts from the rows you count, and gives one row per value found: a journey without reservations has no group at all.
Next: Sub-queries.