Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sub-queries

A query can be used inside another one: as a condition (“there is a journey that leaves from this station”), as a value (“the station of this journey’s last stop”), or as a list (“the stations some planned journey leaves from”). This is Django’s Exists, Subquery and OuterRef.

Many relations and aggregates already write sub-queries for you. Write your own when the relation you need is not declared, when the condition is not along a relation, or when you need a value of one particular related row.

You wantrindSQLDjango
a condition: some row existsquery.exists()EXISTS (…)Exists(qs)
a value from one rowquery.limit(1).scalar(value)(SELECT value … LIMIT 1)Subquery(qs.values("x")[:1])
an aggregate as a valuequery.scalar(func::max(…))(SELECT MAX(…) …)Subquery(qs.annotate(…).values(…))
a number of rows as a valuequery.scalar_count()(SELECT COUNT(*) …)Subquery(… Count …)
a listpath.in_sub(query.select(col))IN (SELECT col …)field__in=qs.values("col")
the row of the query aroundModel::col().outer()the outer table’s columnOuterRef("col")

A condition: exists

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
// The stations a journey leaves from.
let leaving = Query::<Journey>::new()
    .filter(Journey::origin_id().eq(Station::id().outer()))
    .exists();
Query::<Station>::new().filter(leaving)
}
SELECT "t0"."id", …
FROM "network_station" AS "t0"
WHERE EXISTS (SELECT 1 FROM "timetable_journey" AS "t1" WHERE "t1"."origin_id" = "t0"."id")
-- → stations 1, 2, 3

Two new pieces:

  • .exists() turns a query into a condition: EXISTS (…). It is true when the query finds at least one row.
  • .outer() on a path means “the column of the query around this one”: here, the station being tested. It is Django’s OuterRef("id"). Without it, Station::id() inside a query on journeys would be refused, since it is not a column of the journeys.

The opposite is !:

#![allow(unused)]
fn main() {
Query::<Station>::new().filter(!leaving)
// WHERE NOT EXISTS (…)                                     → stations 4, 5, 6
}

This example is the same as Station::departures().any(|_| …) would be, if the relation were declared. Use the relation when it exists; write the sub-query when it does not, or when the condition is not an equality of keys.

How outer() finds its query

.outer() refers to the nearest enclosing query on that column’s table, however many queries out. So it works two levels down:

#![allow(unused)]
fn main() {
// Stations from which a journey leaves that stops somewhere else than at this station.
Query::<Station>::new().filter(
    Query::<Journey>::new()
        .filter(
            Journey::origin_id().eq(Station::id().outer())
                & Query::<Stop>::new()
                    .filter(Stop::journey_id().eq(Journey::id().outer())
                        & Stop::station_id().ne(Station::id().outer()))
                    .exists(),
        )
        .exists(),
)
}
WHERE EXISTS (SELECT 1 FROM "timetable_journey" AS "t1" WHERE "t1"."origin_id" = "t0"."id"
  AND EXISTS (SELECT 1 FROM "timetable_stop" AS "t2"
              WHERE "t2"."journey_id" = "t1"."id" AND "t2"."station_id" <> "t0"."id"))
-- → stations 1, 2, 3

Journey::id().outer() is the journey of the middle query, and Station::id().outer() the station of the outermost one.

It works even when both queries are on the same table: inside a sub-query on wagons, Wagon::train_id().outer() is the wagon of the outer query.

#![allow(unused)]
fn main() {
// The biggest wagon of each train.
Query::<Wagon>::new().filter(
    Wagon::capacity().eq(
        Query::<Wagon>::new()
            .filter(Wagon::train_id().eq(Wagon::train_id().outer()))
            .scalar(func::max(Wagon::capacity())),
    ),
)
}
WHERE "t0"."capacity" = (SELECT MAX("t1"."capacity") FROM "fleet_wagon" AS "t1"
                         WHERE "t1"."train_id" = "t0"."train_id")
-- → wagons 1, 4, 6

A value: scalar

query.scalar(value) turns a query into a value: the query must give at most one row, and value is what it selects. With no row, the value is NULL.

The station of each journey’s last stop: order the stops, keep one, read its station.

#![allow(unused)]
fn main() {
let last_station = Query::<Stop>::new()
    .filter(Stop::journey_id().eq(Journey::id().outer()))
    .order_by([Stop::rank().desc()])
    .limit(1)
    .scalar(Stop::station_id().expr());

let select = Query::<Journey>::new()
    .select((Journey::id(), last_station.as_("last_station")))
    .order_by([Journey::id().asc()])
    .into_select();
let rows: Vec<(i64, Option<i64>)> = db.rows(&select).await?;
}
SELECT "t0"."id",
  (SELECT "t1"."station_id" FROM "timetable_stop" AS "t1"
   WHERE "t1"."journey_id" = "t0"."id" ORDER BY "t1"."rank" DESC LIMIT 1) AS "last_station"
FROM "timetable_journey" AS "t0"
ORDER BY "t0"."id"
-- → [(1, Some(2)), (2, Some(1)), (3, Some(2)), (4, None)]

This is the classic Django pattern annotate(last=Subquery(Stop.objects.filter(journey=OuterRef("pk")).order_by("-rank").values("station")[:1])).

  • scalar takes an expression: .expr() turns the path into one.
  • limit(1) is needed when several rows could match: a scalar sub-query that returns two rows is an error in PostgreSQL (“more than one row returned by a subquery”).
  • Journey 4 has no stop, so its value is NULL: read it as an Option.

An aggregate as a value

#![allow(unused)]
fn main() {
let max_capacity = Query::<Wagon>::new()
    .filter(Wagon::train_id().eq(Train::id().outer()))
    .scalar(func::max(Wagon::capacity()));
Query::<Train>::new().select((Train::id(), max_capacity))
// → [(1, Some(4)), (2, Some(1000)), (3, Some(50))]
}

An aggregate always gives one row, so no limit is needed. (When the relation is declared, Train::wagons().rows().max(|w| w.capacity()) says the same: Aggregates.)

A count as a value: scalar_count

#![allow(unused)]
fn main() {
let booked = Query::<Reservation>::new()
    .filter(Reservation::journey_id().eq(Journey::id().outer()) & Reservation::status().eq("booked"))
    .scalar_count();

Query::<Journey>::new().select((Journey::code(), booked.clone()))
// SELECT "t0"."code", (SELECT COUNT(*) FROM "booking_reservation" AS "t1"
//                      WHERE "t1"."journey_id" = "t0"."id" AND "t1"."status" = $1)
// → [("J100", 3), ("J200", 1), ("J300", 0), ("J400", 0)]

Query::<Journey>::new().filter(booked.ge(2))       // → journey 1
}

Using a value

A scalar sub-query is an expression like any other: it is selected, compared, ordered by, and combined with arithmetic. Give it a name with as_ when you select it and another query must read it by name.

A list: in_sub

path.in_sub(query) is IN (SELECT …). The query must select one column:

#![allow(unused)]
fn main() {
// The stations from which a planned journey leaves.
let origins = Query::<Journey>::new()
    .filter(Journey::status().eq("planned"))
    .select(Journey::origin_id());
Query::<Station>::new().filter(Station::id().in_sub(origins))
}
WHERE "t0"."id" IN (SELECT "t1"."origin_id" FROM "timetable_journey" AS "t1" WHERE "t1"."status" = $1)
-- → stations 1, 2

This is Django’s filter(id__in=Journey.objects.filter(…).values("origin_id")). The sub-query is not correlated: it does not need outer(), and PostgreSQL runs it once.

in_sub takes anything that turns into a Select: a query with one selected column, a tree walk (Region::subtree(2)), a CTE’s select("col").

It is also the way to update or delete rows through a relation.

exists, in_sub or a relation?

SituationWrite
the relation is declaredthe relation: Station::departures().any(…), .count()
“some row of another table points here”exists() with outer()
“the key is in this list of keys”in_sub
a value of one related rowscalar with order_by and limit(1)
a count or sum as a valuethe relation’s aggregate, or scalar_count, scalar(func::…)

EXISTS and IN (SELECT …) usually give the same plan in PostgreSQL. Choose the one that reads best.

Next: Loading related rows.