Aggregates, annotations, subqueries, and windows
How do annotate, aggregate, Subquery, OuterRef, and Window alter the compiled SQL — and why can two unrelated Count annotations silently multiply each other’s totals?
So far every query we compiled kept a clean one-to-one shape: one base "Story" row in "FROM" produced at most one output row in "SELECT". The moment you ask SQL to summarize across related tables — with QuerySet, QuerySet, Subquery, OuterRef, Exists, or Window — the relational algebra shifts underneath your feet. And one innocent-looking annotate() call hides the single most famous data-corruption bug in Django ORM code: join fan-out.
The Cartesian join fan-out trap on "desk/"
In our seeded newsroom, "bridge-bond-passes" has 2 "Correction" rows and 2 "Beat" rows ("transit", "budget"), while "city-budget-hearing" has 1 "Correction" row and 2 "Beat" rows ("budget", "housing"). Now annotate every "Story" with Count("corrections") and Count("beats") in the same queryset:
ch08-sql and ch08-bench. Notice the two-stage failure: naive Count returns wrong numbers (4, 4 instead of 2, 2), and even after adding distinct=True, SQL still builds an O(N^2) Cartesian product of 18,000 intermediate rows at N=30 while correlated Subquery stays flat at 1.213 ms (4.61x faster).Why does join fan-out happen? Because QuerySet attaches both Count("corrections") and Count("beats") to the same Query, forcing two independent "LEFT OUTER JOIN"s onto "newsroom_story" before "GROUP BY" runs. Every correction row pairs with every beat row for that story, multiplying 2 × 2 = 4 rows for "bridge-bond-passes" and 1 × 2 = 2 rows for "city-budget-hearing". Worse still, every story with zero corrections ("water-main-repair", "riverfront-stadium-lease", "night-bus-schedule", "zoning-board-tables-plan") produces "NULL" on "newsroom_correction"."id" — which "COUNT(col)" ignores — so four of our six rows look completely right while the two busiest stories silently report bogus totals!
Adding distinct=True (Count("corrections", distinct=True)) rescues Count by deduplicating primary keys inside the aggregate, but it has two fatal limits: it cannot rescue Sum (two identical line-item prices would collapse into one!), and the database engine still materializes the N × M cross-product before deduplicating it.
How Subquery, OuterRef, and Exists isolate each relation
The clean relational fix is Subquery paired with OuterRef — or Exists when you only need a boolean presence check.
Trace what happens inside Subquery and Subquery.as_sql:
- Inside the inner queryset (
"Correction),.objects .filter(story=OuterRef('pk'))" OuterRef("pk")stays unresolved during inner-query construction and converts intoResolvedOuterRef("pk")whenOuterRefruns against the inner.resolve_expression Query. - When the outer
Queryresolves theSubquery,Querywalks every table alias in the inner.bump_prefix Queryand advances its prefix letter from"T"to"U"("U0","U1", ..., or"V0"inside a doubly-nested subquery), guaranteeing that inner table aliases can never collide with outer aliases. - Finally,
ResolvedOuterRefresolves.as_sql "pk"against the outer compiler ("newsroom_story"."id"), whileExists.as_sqladds"SELECT 1 AS a ... LIMIT 1"so the database stops scanning at the very first matching child row!
Watch naive fan-out, distinct=True, correlated Subquery, and Exists side by side on "desk/":
7. Aggregates, join fan-out, Subquery, Exists, and Window QUALIFY
fanout_sql = SELECT "newsroom_story"."slug" AS "slug", COUNT("newsroom_correction"."id") AS "n_corr", COUNT("newsroom_storybeat"."beat_id") AS "n_beats" FROM "newsroom_story" LEFT OUTER JOIN "newsroom_correction" ON ("newsroom_story"."id" = "newsroom_correction"."story_id") LEFT OUTER JOIN "newsroom_storybeat" ON ("newsroom_story"."id" = "newsroom_storybeat"."story_id") GROUP BY "newsroom_story"."id", "newsroom_story"."headline", 1, "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id" ORDER BY "newsroom_story"."id" ASC
fanout_rows = [('bridge-bond-passes', 4, 4), ('water-main-repair', 0, 1), ('city-budget-hearing', 2, 2), ('riverfront-stadium-lease', 0, 1), ('night-bus-schedule', 0, 1), ('zoning-board-tables-plan', 0, 1)]
distinct_rows = [('bridge-bond-passes', 2, 2), ('water-main-repair', 0, 1), ('city-budget-hearing', 1, 2), ('riverfront-stadium-lease', 0, 1), ('night-bus-schedule', 0, 1), ('zoning-board-tables-plan', 0, 1)]
subquery_sql = SELECT "newsroom_story"."slug" AS "slug", (SELECT COUNT("U0"."id") AS "c" FROM "newsroom_correction" "U0" WHERE "U0"."story_id" = ("newsroom_story"."id") GROUP BY "U0"."story_id") AS "n_corr", (SELECT COUNT("U0"."id") AS "c" FROM "newsroom_beat" "U0" INNER JOIN "newsroom_storybeat" "U1" ON ("U0"."id" = "U1"."beat_id") WHERE "U1"."story_id" = ("newsroom_story"."id") GROUP BY "U1"."story_id") AS "n_beats" FROM "newsroom_story" ORDER BY "newsroom_story"."id" ASC
subquery_rows = [('bridge-bond-passes', 2, 2), ('water-main-repair', None, 1), ('city-budget-hearing', 1, 2), ('riverfront-stadium-lease', None, 1), ('night-bus-schedule', None, 1), ('zoning-board-tables-plan', None, 1)]
exists_sql = SELECT "newsroom_story"."slug" AS "slug", EXISTS(SELECT %s AS "a" FROM "newsroom_correction" "U0" WHERE "U0"."story_id" = ("newsroom_story"."id") LIMIT 1) AS "has_corr" FROM "newsroom_story" ORDER BY "newsroom_story"."id" ASC
exists_rows = [('bridge-bond-passes', True), ('water-main-repair', False), ('city-budget-hearing', True), ('riverfront-stadium-lease', False), ('night-bus-schedule', False), ('zoning-board-tables-plan', False)]
Catch two sharp details right inside "subquery_rows" and "fanout_sql":
- Notice why
"water-main-repair"returnedNonefor"n_corr"under theSubqueryinstead of0: because the inner query used"GROUP BY U0, zero matching corrections produce zero subquery rows, which SQL turns into.story_id" "NULL"in a scalar subquery! Always wrap grouped scalarSubquerycounts inCoalesce(Coalesce, defaulting toValue(0)) if you want0rather thanNone. - Notice also
"order_by()"on the inner subquery: without clearing"Meta.ordering", Django would either inject an unnecessary"ORDER BY"inside the subquery or pull extra columns into"GROUP BY". And in"fanout_sql", notice howSQLCompilerreplaced.get_group_by "newsroom_story"."slug"with ordinal1because SQLite supports"GROUP BY"select-position indexes (allows_group_by_select_index).
And look at the measured scaling numbers from ch08-bench across 20 stories as each story gains N beats and N corrections:
2. Join fan-out scaling: 20 stories x (N beats * N corrections), 7 trials (ms)
N_each joined_rows distinct_ms subquery_ms speedup
5 500 0.842 1.201 0.70x
10 2000 1.163 1.161 1.00x
20 8000 2.952 1.174 2.51x
30 18000 5.590 1.213 4.61x
At N = 5 (500 joined rows), compiling two nested Subquery trees costs slightly more Python overhead (1.201 ms vs. 0.842 ms). By N = 10 (2,000 rows), the curves cross (1.163 ms vs. 1.161 ms). By N = 30 (18,000 rows), Count(..., distinct=True) climbs to 5.590 ms while correlated Subquery barely budges (1.213 ms, 4.61x faster).
Query.get_aggregation and Window + "QUALIFY" rewrites
Two remaining compiler rewrites show how far Django bends a flat Query when SQL syntax forbids doing something in one layer:
QuerySet(.aggregate Query,.get_aggregation Query): Unlike.get_aggregation annotate(which adds one column per row and emits"GROUP BY"),aggregatemust collapse the whole queryset into a single dictionary. If the queryset is already grouped, sliced ("qs[:10]"),"DISTINCT", combined ("UNION"), or already contains an aggregate,Subquery, orWindowannotation (lines 520–530),get_aggregationrefuses to stack a second"GROUP BY"on top — it clones the query intoinner_queryand wraps it inside anAggregateQueryso the outer query aggregates overFROM (inner_query) subquery!WindowandSQLCompiler: A.get_qualify_sql Windowwraps a window-compatible function such asRowNumberwith"PARTITION BY","ORDER BY", and an optionalRowRange/ValueRangeframe — critically setting"contains_aggregate = False"and"contains_over_clause = True"so it computes ranks per partition without collapsing rows into"GROUP BY". Because standard SQL (and SQLite / PostgreSQL) forbids filtering on a window function inside"WHERE"directly, when you chain"filter(desk_rank=1)"on aWindowannotation,WhereNoderoutes that predicate into.split_having_qualify "qualify"andSQLCompilerrewrites the entire query into a derived table (.get_qualify_sql "qualify"— plus an outer"qualify_mask"wrapper to strip internal ordering columns while preserving"ORDER BY"!):
split_having_qualify -> where=False having=False qualify=True
window_qualify_sql = SELECT "desk__slug", "slug", "priority", "desk_rank" FROM ( SELECT * FROM ( SELECT "newsroom_desk"."slug" AS "desk__slug", "newsroom_story"."slug" AS "slug", "newsroom_story"."priority" AS "priority", ROW_NUMBER() OVER (PARTITION BY "newsroom_story"."desk_id" ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC) AS "desk_rank", "newsroom_story"."desk_id" AS "qual0" FROM "newsroom_story" INNER JOIN "newsroom_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") ORDER BY "newsroom_story"."desk_id" ASC ) "qualify" WHERE "desk_rank" = %s ) "qualify_mask" ORDER BY "qual0" ASC
window_qualify_params = (1,)
window_qualify_rows = [('metro', 'bridge-bond-passes', 1, 1), ('city-hall', 'city-budget-hearing', 1, 1), ('sports', 'riverfront-stadium-lease', 3, 1)]
Look at that single query cleanly returning the top-priority lead story for each of "desk/"'s three desks ("metro", "city-hall", "sports") in one round-trip — without a single line of hand-written SQL.
Once SQLCompiler hands back its (sql, params) tuple, the Python-to-SQL compiler’s job is done. Now Django has to push those bytes across a live database connection inside the right transaction boundary — and keep the physical database tables in sync with evolving Python models. We cross that boundary next in Connections, transactions, and migrations.