Django 6.1.3

8.7 From Python to SQL

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.annotate, QuerySet.aggregate, 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:

Figure 8.3 Every corrupted count, SQL alias, and millisecond bar is parsed directly from 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.annotate 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.resolve_expression and Subquery.as_sql:

  1. Inside the inner queryset ("Correction.objects.filter(story=OuterRef('pk'))"), OuterRef("pk") stays unresolved during inner-query construction and converts into ResolvedOuterRef("pk") when OuterRef.resolve_expression runs against the inner Query.
  2. When the outer Query resolves the Subquery, Query.bump_prefix walks every table alias in the inner Query and 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.
  3. Finally, ResolvedOuterRef.as_sql resolves "pk" against the outer compiler ("newsroom_story"."id"), while Exists.as_sql adds "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/":

Recorded on Django 6.1.3 ch08-sql script
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":

And look at the measured scaling numbers from ch08-bench across 20 stories as each story gains N beats and N corrections:

Recorded on Django 6.1.3 ch08-bench script
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:

Recorded on Django 6.1.3 ch08-sql script
  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.