Ordering and pages
order_by
#![allow(unused)]
fn main() {
Query::<Station>::new().order_by([Station::city().asc(), Station::name().desc()])
}
ORDER BY "t0"."city", "t0"."name" DESC
order_by takes a list of order items: a path (or an expression)
followed by .asc() or .desc(). This is Django’s
order_by("city", "-name").
There is no default order. A model has no Meta.ordering, so a query
without order_by comes back in whatever order PostgreSQL finds
convenient, which can change from one run to the next. Order every query
whose order matters.
Coming from Django: a resource says its default order with
#[ordering(.., default("name"))], and always ends it with the primary key (Filters). In your own queries, the order is yours to give.
Adding to the order, or replacing it
order_by adds to the order the query already has. reorder
replaces it:
#![allow(unused)]
fn main() {
Query::<Station>::new()
.order_by([Station::city().asc()])
.reorder([Station::platforms().desc()])
// ORDER BY "t0"."platforms" DESC
}
Django’s order_by replaces; rind’s order_by adds, so that a scope can
give an order and a caller can refine it (order_by([…id().asc()]) to
break ties). Use reorder when a caller must impose its own.
What can order
Any path or expression:
#![allow(unused)]
fn main() {
// through a relation: joined like a filter
Query::<Station>::new().order_by([Station::region().name().asc(), Station::id().asc()])
// INNER JOIN "network_region" AS "region" ON "region"."id" = "t0"."region_id"
// ORDER BY "region"."name", "t0"."id" → 2, 3, 4, 1, 6, 5
// an expression
Query::<Station>::new().order_by([(Station::platforms() * 2 - 1).desc()])
// ORDER BY (("t0"."platforms" * $1) - $2) DESC
// an aggregate of a many relation: the number of departures
Query::<Station>::new().order_by([Station::departures().count().desc(), Station::id().asc()])
// ORDER BY (SELECT COUNT(*) FROM "timetable_journey" AS "t1" WHERE "t1"."origin_id" = "t0"."id") DESC, "t0"."id"
}
Ordering by an aggregate is what Django does with
annotate(n=Count("departures")).order_by("-n"). On a large table, add
.grouped() to the relation (Aggregates).
NULLs in the order
PostgreSQL puts NULLs last in an ascending order, and first in a
descending one:
#![allow(unused)]
fn main() {
Query::<Station>::new().order_by([Station::opened().asc()])
// → 1 (1840), 2 (1857), 6 (1931), then 3, 4, 5 (no date)
}
To choose otherwise, order by an expression:
func::coalesce(Station::opened(), some_date) puts the stations without
a date where that date would be (Expressions).
Ties
Rows that have the same values for every item of the order come in any order. When the order decides what a page holds, end it with something unique, usually the key:
#![allow(unused)]
fn main() {
.order_by([Station::city().asc(), Station::id().asc()])
}
Without it, two pages of the same list may show the same row, and another row on neither.
Pages: limit and offset
#![allow(unused)]
fn main() {
Query::<Station>::new()
.order_by([Station::city().asc(), Station::name().desc()])
.offset(2)
.limit(2)
}
ORDER BY "t0"."city", "t0"."name" DESC
LIMIT 2
OFFSET 2
Stations 1 and 4: the third and fourth, by city. This is Django’s
qs[2:4]. limit and offset take a u64.
db.count(&q) leaves out the order, the limit and the offset: it counts
what the filters keep, which is what a page of results needs beside it.
#![allow(unused)]
fn main() {
let page = 3;
let size = 20;
let q = Query::<Station>::new().filter(…).order_by([Station::name().asc(), Station::id().asc()]);
let total = db.count(&q).await?;
let rows = db.all(&q.offset((page - 1) * size).limit(size)).await?;
}
A resource does all this for its lists, with ?page=
and ?page_size=.
OFFSET reads and skips the rows before the page. Deep pages of a large
table are slow; to walk a whole table, filter on the key instead
(Station::id().gt(last_seen)) and order by it.
Next: Choosing the columns.