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

# Inner vs. outer joins and multi-valued filter traps

Why do combining two lookups in one `QuerySet.filter` call and chaining two separate `QuerySet.filter` calls across a many-to-many relation generate completely different SQL and different row counts?

Every Django developer eventually hits this moment: you refactor a long `QuerySet.filter` (`django/db/models/query.py:QuerySet.filter`) into two readable chained `"filter(...).filter(...)"` calls — or collapse two chained calls into one — and a test suite that used to pass starts returning different rows.

On `"desk/"`, every `"Story"` links to `"Beat"` rows through `"StoryBeat"` (storing `"primary"` and `"position"` on the join table). In our seeded newsroom:
- `"bridge-bond-passes"` has **two** `"StoryBeat"` rows: `"transit"` (`primary=True`) and `"budget"` (`primary=False`).
- `"city-budget-hearing"` has **two** `"StoryBeat"` rows: `"budget"` (`primary=True`) and `"housing"` (`primary=False`).

Now ask two seemingly identical questions: find stories with `"story_beats__primary=True"` and `"story_beats__beat__slug='budget'"`. Put both keyword arguments in **one** `QuerySet.filter` call and Django returns **1 story** (`"city-budget-hearing"`). Split them across **two chained** `QuerySet.filter` calls and Django returns **2 stories** (`"bridge-bond-passes"` and `"city-budget-hearing"`).

## Single vs. chained filters across a multi-valued relation

```text figure=multivalued-join-trap
Multi-valued M2M join reuse & JoinPromoter transitions on desk/ (Django 6.1.3)

1. Single filter() reuses one StoryBeat join alias vs. chained filter() spawns alias T3:
   SINGLE:  filter(story_beats__primary=True, story_beats__beat__slug='budget')
            alias_map: story -> storybeat (INNER, ref=2) -> beat (INNER, ref=1)
            result:    1 row -> ['city-budget-hearing']  (same StoryBeat row satisfies both)

   CHAINED: filter(story_beats__primary=True).filter(story_beats__beat__slug='budget')
            alias_map: story -> storybeat (INNER, ref=1) AND story -> T3 [storybeat] -> beat
            result:    2 rows -> ['bridge-bond-passes', 'city-budget-hearing']

2. JoinPromoter votes on nullable Reporter.user (INNER <-> LEFT OUTER):
   A. user__username='editor'                     -> auth_user: INNER JOIN       ['Ada']
   B. Q(user__username='editor') | Q(name='Bram') -> auth_user: LEFT OUTER JOIN  ['Ada', 'Bram']
   C. (...) & Q(user__is_active=True)             -> auth_user: INNER JOIN       ['Ada']
```

*Every table alias, reference count, join type, and returned row is verified directly against `ch08-sql`. Notice why `"bridge-bond-passes"` appears only on the right: it has a primary beat (`"transit"`) on one `"StoryBeat"` row and a `"budget"` beat (`primary=False`) on a second `"StoryBeat"` row.*

A **multi-valued relation** is any reverse foreign key or many-to-many edge (`PathInfo.m2m == True`) where one row on the left table can match *zero, one, or many* rows on the right table. Look at the single line inside `Query.setup_joins` (`django/db/models/sql/query.py:Query.setup_joins`) that creates the entire divergence:

```python
reuse = can_reuse if join.m2m else None
alias = self.join(connection, reuse=reuse)
```

When `"join.m2m"` is `False` (a forward foreign key like `"Story.desk"`), `setup_joins` passes `"reuse=None"` — telling `Query.join` (`django/db/models/sql/query.py:Query.join`) to reuse *any* existing join to `"newsroom_desk"`. When `"join.m2m"` is `True` (such as `"Story -> StoryBeat"`), `setup_joins` restricts reuse strictly to `"can_reuse"`.

Where does `"can_reuse"` come from? Inside `Query.add_q` (`django/db/models/sql/query.py:Query.add_q`), Django snapshots `"existing_inner"` from `"alias_map"` before processing the `Q` object, and inside `Query._add_q` (`django/db/models/sql/query.py:Query._add_q`) it passes `"used_aliases"` as `"can_reuse"` for every sibling predicate *within that single `filter()` call*, adding each newly created multi-valued alias into `"used_aliases"` as it goes:

- Inside **one** `filter(story_beats__primary=True, story_beats__beat__slug='budget')` call, the first keyword creates `"newsroom_storybeat"` and records it in `"used_aliases"`. The second keyword runs in the same `_add_q` call, finds `"newsroom_storybeat"` inside `"can_reuse"`, increments its refcount to `2`, and tests *both* conditions against the **same** `"StoryBeat"` row.
- Across **two chained** `"filter(...).filter(...)"` calls, `Query.chain` (`django/db/models/sql/query.py:Query.chain`) resets `"used_aliases = set()"`. The second call sees an empty `"can_reuse"` set, refuses to reuse `"newsroom_storybeat"`, and asks `Query.table_alias` for a fresh alias — **`"T3"`** — joining `"newsroom_storybeat"` a **second time** so two different `"StoryBeat"` rows on the same `"Story"` can independently satisfy the two filters!

Inspect both live `"alias_map"` tables and compiled SQL statements side by side on `"desk/"`:

```text recording=ch08-sql
5. Join promotion, multi-valued M2M trap, and split_exclude
  single_filter: filter(story_beats__primary=True, story_beats__beat__slug='budget')
    alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=2
    alias='newsroom_storybeat' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=2
    alias='newsroom_beat' kind=Join join_type='INNER JOIN' parent='newsroom_storybeat' table='newsroom_beat' nullable=False refcount=1
    table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_storybeat': ['newsroom_storybeat'], 'newsroom_beat': ['newsroom_beat']}
    sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "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" FROM "newsroom_story" INNER JOIN "newsroom_storybeat" ON ("newsroom_story"."id" = "newsroom_storybeat"."story_id") INNER JOIN "newsroom_beat" ON ("newsroom_storybeat"."beat_id" = "newsroom_beat"."id") WHERE ("newsroom_beat"."slug" = %s AND "newsroom_storybeat"."primary" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
    params = ('budget', True)
    slugs = ['city-budget-hearing']
  chained_filter: filter(story_beats__primary=True).filter(story_beats__beat__slug='budget')
    alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=2
    alias='newsroom_storybeat' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=1
    alias='T3' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_storybeat' nullable=True refcount=1
    alias='newsroom_beat' kind=Join join_type='INNER JOIN' parent='T3' table='newsroom_beat' nullable=False refcount=1
    table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_storybeat': ['newsroom_storybeat', 'T3'], 'newsroom_beat': ['newsroom_beat']}
    sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "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" FROM "newsroom_story" INNER JOIN "newsroom_storybeat" ON ("newsroom_story"."id" = "newsroom_storybeat"."story_id") INNER JOIN "newsroom_storybeat" "T3" ON ("newsroom_story"."id" = "T3"."story_id") INNER JOIN "newsroom_beat" ON ("T3"."beat_id" = "newsroom_beat"."id") WHERE ("newsroom_storybeat"."primary" = %s AND "newsroom_beat"."slug" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
    params = (True, 'budget')
    slugs = ['bridge-bond-passes', 'city-budget-hearing']
```

Beware one bonus side effect on chained multi-valued filters: if a story had *two* primary beats and *two* matching beats, joining `"newsroom_storybeat"` twice can emit **duplicate `"Story"` rows** in the result unless you append `QuerySet.distinct` (or filter with `Exists`).

## Join promotion and demotion via `JoinPromoter`

Every new `Join` (`django/db/models/sql/datastructures.py:Join`) starts life in `Query.setup_joins` as an **`"INNER JOIN"`** — the fastest join type for the SQL planner. Upgrading an `"INNER JOIN"` to a **`"LEFT OUTER JOIN"`** (so rows without a matching joined record are not silently discarded) is called **join promotion**, managed by `JoinPromoter` (`django/db/models/sql/query.py:JoinPromoter`) together with `Query.promote_joins` (`django/db/models/sql/query.py:Query.promote_joins`) and `Query.demote_joins` (`django/db/models/sql/query.py:Query.demote_joins`).

`JoinPromoter` works like a tiny election over every `Q` branch. First it folds negation via De Morgan's law (`"effective_connector"` flips `"NOT (a AND b)"` into `"OR"` and `"NOT (a OR b)"` into `"AND"`). Each child filter votes for the table aliases that *must* be non-null for that child to match. Then `JoinPromoter.update_join_types` applies two exact rules:

- **Promote (`Query.promote_joins`):** Under an effective `"OR"`, if an alias received *fewer* votes than `"num_children"` (`votes < num_children`), an `"INNER JOIN"` on that alias would discard valid rows that matched a different `"OR"` branch! `promote_joins` walks `"alias_map"` from that alias outward through every descendant join, calling `Join.promote` (`django/db/models/sql/datastructures.py:Join.promote`) wherever the join is nullable (`"nullable=True"` on nullable foreign keys or any reverse relation).
- **Demote (`Query.demote_joins`):** Under an effective `"AND"` — or an `"OR"` where *every* branch voted for the alias (`votes == num_children`) — a row with `"NULL"` on that join can never pass the surrounding clause anyway, so `demote_joins` safely calls `Join.demote` (`django/db/models/sql/datastructures.py:Join.demote`) to turn `"LEFT OUTER JOIN"` right back into `"INNER JOIN"` for the optimizer!

## Nullable `exclude()` and `split_exclude` on multi-valued relations

Two negation subtleties finish the picture in `Query.build_filter` (`django/db/models/sql/query.py:Query.build_filter`). First, in SQL three-valued logic, `"NOT (NULL = '2026-11-25 10:15:00')"` evaluates to `"UNKNOWN"` (falsey!) — so a naive `"WHERE NOT (published_at = %s)"` would silently drop every draft `"Story"` whose `"published_at"` is `"NULL"`! Whenever `"current_negated"` is `True` on a nullable column, `build_filter` (lines 1630–1647) appends `"AND col IS NOT NULL"` *inside* the `"NOT (...)"`, turning `"NULL"` rows into `NOT (UNKNOWN AND FALSE) -> NOT FALSE -> TRUE` so drafts survive.

Second, negating a multi-valued relation (`"Story.objects.exclude(beats__slug='budget')"`) cannot simply negate a flat `"JOIN"` — if `"bridge-bond-passes"` has both `"transit"` and `"budget"`, a joined row for `"transit"` would satisfy `"beat.slug != 'budget'"` and leak `"bridge-bond-passes"` right back into the excluded result! So when `"branch_negated"` is `True`, `build_filter` calls `Query.setup_joins(..., allow_many=False)` (`django/db/models/sql/query.py:Query.names_to_path`), which immediately raises **`MultiJoin`** (`django/db/models/sql/datastructures.py:MultiJoin`). `build_filter` catches `MultiJoin` and delegates to **`Query.split_exclude`** (`django/db/models/sql/query.py:Query.split_exclude`), which trims the leading path (`Query.trim_start`), bumps subquery aliases to `"U1"` / `"U2"`, and compiles a correlated **`"NOT (EXISTS(...))"`** subquery!

Watch `JoinPromoter`, nullable `exclude()`, and `split_exclude` all execute live on `"desk/"`:

```text recording=ch08-sql
  promote_inner: auth_user='INNER JOIN' names=['Ada']
  promote_or: auth_user='LEFT OUTER JOIN' names=['Ada', 'Bram']
  demote_and: auth_user='INNER JOIN' names=['Ada']
  exclude_nullable_sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "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" FROM "newsroom_story" WHERE NOT ("newsroom_story"."published_at" = %s AND "newsroom_story"."published_at" IS NOT NULL) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
  exclude_nullable_params = ('2026-11-25 10:15:00',)
  exclude_nullable_slugs = ['city-budget-hearing', 'night-bus-schedule', 'water-main-repair', 'zoning-board-tables-plan', 'riverfront-stadium-lease']
  split_exclude_sql = SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "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" FROM "newsroom_story" WHERE NOT (EXISTS(SELECT %s AS "a" FROM "newsroom_storybeat" "U1" INNER JOIN "newsroom_beat" "U2" ON ("U1"."beat_id" = "U2"."id") WHERE ("U2"."slug" = %s AND "U1"."story_id" = ("newsroom_story"."id")) LIMIT 1)) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
  split_exclude_params = (1, 'budget')
  split_exclude_slugs = ['night-bus-schedule', 'water-main-repair', 'zoning-board-tables-plan', 'riverfront-stadium-lease']
```

Look at `"zoning-board-tables-plan"` sitting safely inside `"exclude_nullable_slugs"` despite `"published_at=None"`, and look at `"split_exclude_sql"` cleanly excluding both `"bridge-bond-passes"` and `"city-budget-hearing"` via `"NOT (EXISTS(... LIMIT 1))"` using bumped aliases `"U1"` and `"U2"`.

With `"alias_map"`, `"where"`, `"select"`, and join types all finalized inside `Query`, we are ready for the moment Django finally writes SQL text, binds parameters, and decodes cursor rows — next in [SQLCompiler.as_sql and parameter binding](compiler.md).
