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

# Inside Query: alias maps and table joins

What data structures does `Query` hold — `alias_map`, `alias_refcount`, `table_map`, `select`, `where` — and how does it avoid duplicate table aliases?

When you chain methods on a `QuerySet` (`django/db/models/query.py:QuerySet`), the object actually mutating behind the scenes is a **`Query`** (`django/db/models/sql/query.py:Query`). A `Query` is an in-memory relational plan, independent of any SQL dialect: it knows nothing about SQLite's `"?"` placeholders or PostgreSQL's `"DISTINCT ON"`, only about models, columns, boolean trees, and a directed graph of joined tables.

## The five tables inside `Query.__init__`

Open `Query.__init__` (`django/db/models/sql/query.py:Query.__init__`) and look at the five join-tracking dictionaries allocated for every new query alongside `"where"` (`WhereNode`, `django/db/models/sql/where.py:WhereNode`), `"select"`, `"annotations"`, `"order_by"`, `"group_by"`, and `"low_mark"` / `"high_mark"`:

| Attribute on `Query` | Structure and responsibility |
| --- | --- |
| **`alias_map`** | Ordered `dict[alias, BaseTable \| Join]` defining every table in the `"FROM"` clause and the exact join edge connecting it to its parent alias. |
| `"alias_refcount"` | `dict[alias, int]` counting live references to each alias; aliases whose count drops to `0` stay in `"alias_map"` but are skipped by SQL generation. |
| `"table_map"` | `dict[db_table, list[alias]]` mapping a physical table name (`"newsroom_storybeat"`) to every alias currently assigned to it (`["newsroom_storybeat", "T3"]`). |
| `"used_aliases"` | `set[alias]` recording aliases touched during the *current* `filter()` call; reset to `set()` by `Query.chain` unless `"filter_is_sticky"` is set. |
| `"external_aliases"` | `dict[alias, bool]` naming outer-query aliases referenced inside a correlated subquery so `SQLCompiler` quotes them without adding them to the inner `"FROM"`. |

Every entry inside **`alias_map`** is either a `BaseTable` (`django/db/models/sql/datastructures.py:BaseTable`) — the root table for `Query.model`, emitted bare after `"FROM"` — or a **`Join`** (`django/db/models/sql/datastructures.py:Join`). A `Join` records six concrete fields: `"table_name"`, `"parent_alias"`, `"table_alias"`, `"join_type"` (`"INNER JOIN"` or `"LEFT OUTER JOIN"`), `"join_field"`, and `"nullable"`. Because Python dictionaries preserve insertion order, iterating `"alias_map"` in `SQLCompiler.get_from_clause` (`django/db/models/sql/compiler.py:SQLCompiler.get_from_clause`) guarantees that every parent alias is emitted before any child `Join` that references it.

## How `Query.table_alias`, `Query.join`, and `Query.trim_joins` avoid useless joins

Whenever `Query.setup_joins` (`django/db/models/sql/query.py:Query.setup_joins`) walks a relation path returned by `Query.names_to_path` (`django/db/models/sql/query.py:Query.names_to_path`), it constructs a candidate `Join` object for every hop and passes it to `Query.join` (`django/db/models/sql/query.py:Query.join`).

Inside `Query.join`, Django checks whether an equivalent `Join` already exists in `"alias_map"` (comparing `Join.__eq__`, which matches `"table_name"`, `"parent_alias"`, `"join_field"`, and any `FilteredRelation` condition — *ignoring* `"join_type"`). For single-valued forward foreign keys, `setup_joins` passes `"reuse=None"` (meaning *any* existing equivalent join is reusable!), so `Query.join` simply increments `"alias_refcount"` on the existing alias and returns it without adding a duplicate table. When no reusable alias exists, `Query.table_alias` (`django/db/models/sql/query.py:Query.table_alias`) allocates the bare table name on first use (`"newsroom_desk"`) and numbered aliases (`"T2"`, `"T3"`, `"T4"`, ...) on subsequent uses of the same physical table.

Now watch a subtle optimization that happens *immediately after* `setup_joins`: **`Query.trim_joins`** (`django/db/models/sql/query.py:Query.trim_joins`). Suppose you write `"Story.objects.filter(desk__id=1)"` instead of `"Story.objects.filter(desk_id=1)"`. `setup_joins` walks the `"desk"` foreign key and creates a `Join` onto `"newsroom_desk"`. Then `trim_joins` inspects the final target column (`"id"` on `"newsroom_desk"`), sees that the foreign-key column `"desk_id"` on `"newsroom_story"` already holds the exact same value on a direct join, swaps the target back to `"newsroom_story.desk_id"`, and calls `Query.unref_alias("newsroom_desk")`.

Inspect two live `Query` objects on `"desk/"` right before SQL compilation — one trimmed, one joined across two tables:

```text recording=ch08-sql
4. Live Query anatomy: alias_map, alias_refcount, and trim_joins
  query: Story.objects.filter(desk__id=metro.id)  [trimmed direct FK join]
    alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=1
    alias='newsroom_desk' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_desk' nullable=False refcount=0
    table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_desk': ['newsroom_desk']}
    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 "newsroom_story"."desk_id" = %s ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
    params = (1,)
  query: Story.objects.filter(desk__slug='metro', reporter__name='Ada')
    alias='newsroom_story' kind=BaseTable table='newsroom_story' refcount=2
    alias='newsroom_desk' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_desk' nullable=False refcount=1
    alias='newsroom_reporter' kind=Join join_type='INNER JOIN' parent='newsroom_story' table='newsroom_reporter' nullable=False refcount=1
    table_map = {'newsroom_story': ['newsroom_story'], 'newsroom_desk': ['newsroom_desk'], 'newsroom_reporter': ['newsroom_reporter']}
    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_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") INNER JOIN "newsroom_reporter" ON ("newsroom_story"."reporter_id" = "newsroom_reporter"."id") WHERE ("newsroom_desk"."slug" = %s AND "newsroom_reporter"."name" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
    params = ('metro', 'Ada')
    slugs = ['bridge-bond-passes', 'night-bus-schedule']
```

Look closely at line 42 of that trace! For `"Story.objects.filter(desk__id=metro.id)"`, `"newsroom_desk"` is **still sitting in `"alias_map"` and `"table_map"`**, with **`refcount=0`**! Because `SQLCompiler.get_from_clause` starts its loop with `"if not self.query.alias_refcount[alias]: continue"`, the zero-refcount join disappears cleanly from SQL — leaving `"FROM newsroom_story WHERE newsroom_story.desk_id = %s"` with zero `"JOIN"`s. Why does `trim_joins` refuse to trim reverse joins (`"if len(joins) == 1 or not info.direct: break"`)? Because on a reverse foreign key, the presence or absence of a matching child row *changes whether the parent row matches*, so trimming the join would alter the query's semantics.

## Lightweight cloning via `Query.clone` and `Query.chain`

Notice one final design detail in `Query.clone` (`django/db/models/sql/query.py:Query.clone`) and `Query.chain` (`django/db/models/sql/query.py:Query.chain`). Rather than calling Python's expensive `copy.deepcopy` on the entire `Query`, `Query.clone` allocates a blank `Empty` shell, sets its `"__class__"`, shallow-copies `"__dict__"`, and explicitly copies only the mutable containers (`"alias_map"`, `"alias_refcount"`, `"table_map"`, `"where"`, `"annotations"`, `"used_aliases"`, `"select_related"`). And right after cloning, `Query.chain` executes one innocent-looking line that governs one of the sharpest semantic traps in the entire ORM:

```python
if not obj.filter_is_sticky:
    obj.used_aliases = set()
```

Every time you chain `"filter(...).filter(...)"`, `"used_aliases"` is wiped clean. On a single-valued foreign key (`"desk"` or `"reporter"`), wiping `"used_aliases"` changes nothing because single-valued joins are always reusable (`"reuse=None"`). On a **many-to-many or reverse foreign-key relation**, wiping `"used_aliases"` forces Django to allocate a brand-new table alias — changing both the compiled SQL and the rows your query returns. That is the exact trap we dissect next in [Inner vs. outer joins and multi-valued filter traps](join-promotion.md).
