---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/db/models/expressions.py:Subquery`), **`OuterRef`** (`django/db/models/expressions.py:OuterRef`), `Exists` (`django/db/models/expressions.py:Exists`), or **`Window`** (`django/db/models/expressions.py: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")` (`django/db/models/aggregates.py:Count`) and `Count("beats")` in the same queryset:

```text figure=count-fanout-vs-subquery
Cartesian join fan-out trap vs. correlated Subquery on desk/ (Django 6.1.3)

1. On bridge-bond-passes (true counts: 2 corrections, 2 beats):
   NAIVE annotate(n_corr=Count('corrections'), n_beats=Count('beats')):
     LEFT JOIN correction (2 rows) x LEFT JOIN storybeat (2 rows) = 4 joined rows before GROUP BY
     Result: ('bridge-bond-passes', 4, 4) and ('city-budget-hearing', 2, 2)  [SILENTLY MULTIPLIED!]

   CORRELATED Subquery + OuterRef('pk'):
     bump_prefix() renames inner aliases T -> U0, U1; zero cross-product (2 + 2 lookups)
     Result: ('bridge-bond-passes', 2, 2) and ('city-budget-hearing', 1, 2)  [EXACT]

2. Scaling across 20 stories as each gets N beats and N corrections (7 trials, ms):
   N =  5 (   500 joined rows):  Count(distinct=True) 0.842 ms  |  Subquery 1.201 ms  (0.70x)
   N = 10 ( 2,000 joined rows):  Count(distinct=True) 1.163 ms  |  Subquery 1.161 ms  (1.00x crossover)
   N = 20 ( 8,000 joined rows):  Count(distinct=True) 2.952 ms  |  Subquery 1.174 ms  (2.51x faster)
   N = 30 (18,000 joined rows):  Count(distinct=True) 5.590 ms  |  Subquery 1.213 ms  (4.61x faster)
```

*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` (`django/db/models/sql/query.py: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`** (`django/db/models/expressions.py:Subquery`) paired with **`OuterRef`** (`django/db/models/expressions.py:OuterRef`) — or **`Exists`** (`django/db/models/expressions.py:Exists`) when you only need a boolean presence check.

Trace what happens inside `Subquery.resolve_expression` (`django/db/models/expressions.py:Subquery.resolve_expression`) and `Subquery.as_sql` (`django/db/models/expressions.py: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")` (`django/db/models/expressions.py:ResolvedOuterRef`) when `OuterRef.resolve_expression` runs against the inner `Query`.
2. When the *outer* `Query` resolves the `Subquery`, `Query.bump_prefix` (`django/db/models/sql/query.py: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/"`:

```text recording=ch08-sql
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"` returned **`None`** for `"n_corr"` under the `Subquery` instead of `0`: because the inner query used `"GROUP BY U0.story_id"`, zero matching corrections produce **zero subquery rows**, which SQL turns into `"NULL"` in a scalar subquery! Always wrap grouped scalar `Subquery` counts in `Coalesce` (`django/db/models/functions/comparison.py:Coalesce`, defaulting to `Value(0)`) if you want `0` rather than `None`.
- 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 how `SQLCompiler.get_group_by` (`django/db/models/sql/compiler.py:SQLCompiler.get_group_by`) replaced `"newsroom_story"."slug"` with ordinal `1` because 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:

```text recording=ch08-bench
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`, `django/db/models/sql/query.py:Query.get_aggregation`):** Unlike `annotate` (which adds one column per row and emits `"GROUP BY"`), `aggregate` must 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`, or `Window` annotation (lines 520–530), `get_aggregation` refuses to stack a second `"GROUP BY"` on top — it clones the query into `inner_query` and wraps it inside an `AggregateQuery` (`django/db/models/sql/subqueries.py:AggregateQuery`) so the outer query aggregates over `FROM (inner_query) subquery`!
- **`Window` (`django/db/models/expressions.py:Window`) and `SQLCompiler.get_qualify_sql` (`django/db/models/sql/compiler.py:SQLCompiler.get_qualify_sql`):** A `Window` wraps a window-compatible function such as `RowNumber` (`django/db/models/functions/window.py:RowNumber`) with `"PARTITION BY"`, `"ORDER BY"`, and an optional `RowRange` / `ValueRange` frame — 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 a `Window` annotation, `WhereNode.split_having_qualify` routes that predicate into `"qualify"` and `SQLCompiler.get_qualify_sql` rewrites the entire query into a derived table (`"qualify"` — plus an outer `"qualify_mask"` wrapper to strip internal ordering columns while preserving `"ORDER BY"`!):

```text recording=ch08-sql
  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](../database.md).
