---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The ORM
promise: ORM calls are SQL in Python clothing.
contents: q-and-where, expressions, lookups, query-object, join-promotion, compiler, subqueries
---

# From Python to SQL

How `Q` objects, expressions, lookups, `Query` join promotion, and `SQLCompiler` compile a Python expression tree into parameterized SQL.

Every Django developer eventually hears the shorthand that ORM calls are just SQL in Python clothing: `"filter"` is `"WHERE"`, `"select_related"` is `"JOIN"`, `"annotate"` is `"SELECT ... AS"`, and `"order_by"` is `"ORDER BY"`.

That shorthand hides the single most important architectural fact about `django/db/models/sql/`: Django is not gluing SQL fragments together as you chain methods. It is building a mutable relational algebra tree — `Q` (`django/db/models/query_utils.py:Q`), `WhereNode` (`django/db/models/sql/where.py:WhereNode`), `BaseExpression` (`django/db/models/expressions.py:BaseExpression`), `Lookup` (`django/db/models/lookups.py:Lookup`), and `Query` (`django/db/models/sql/query.py:Query`) — and only lowering that tree into SQL strings and a separate parameter tuple at the very end inside `SQLCompiler.as_sql` (`django/db/models/sql/compiler.py:SQLCompiler.as_sql`).

That two-phase compiler design explains the sharpest behaviors you will ever hit in production. It explains why `"id__in=[]"` executes **zero** database queries; why `"published_at__year__gte=2026"` rewrites itself into an index-friendly range bound; why splitting two many-to-many predicates across two chained `QuerySet.filter` calls creates a second `"JOIN"` alias and returns completely different rows; why two unrelated `Count` annotations silently multiply each other's totals; and why, on a fast indexed query, **76% to 90% of wall-clock latency is Python compilation rather than SQLite execution**.

## Six stages in Python, and what compilation actually costs

```text figure=python-to-sql-pipeline
Python-to-SQL compilation pipeline & measured cost on Django 6.1.3 (SQLite, 7 trials)

1. Six stages from Python call to parameterized wire SQL:
   1. Q & filter args          -> Q(a) | Q(b), F('priority') + 1 (unresolved Python nodes)
   2. Query.build_filter       -> add_q() -> WhereNode, splitting '__' paths into joins + lookup
   3. Resolve expressions      -> resolve_expression(query): F() -> Col(alias, field) + output_field
   4. Alias map & joins        -> JoinPromoter (INNER <-> LEFT OUTER) + trim_joins (refcount 0 skipped)
   5. SQLCompiler.as_sql       -> compile() -> as_<vendor>, assembling SELECT..FROM..WHERE..LIMIT
   6. Wire & field converters  -> (sql, params), SQLite %s -> ?, cursor.execute + get_db_converters

2. Python Query + as_sql() compile time vs. raw SQLite execution (values_list('id', flat=True)):
   simple_filter            compile 184.6 us  |  SQLite 19.1 us  |  total 244.0 us  (75.7% compile)
   two_fk_joins             compile 281.0 us  |  SQLite 21.1 us  |  total 346.5 us  (81.1% compile)
   m2m_chained_2_aliases    compile 342.0 us  |  SQLite 23.0 us  |  total 402.4 us  (85.0% compile)
   correlated_exists        compile 524.9 us  |  SQLite 19.0 us  |  total 585.5 us  (89.7% compile)
   window_qualify           compile 729.9 us  |  SQLite 34.9 us  |  total 900.5 us  (81.0% compile)
```

*Every latency bar is parsed directly from `ch08-bench`, comparing identical `"values_list('id', flat=True)"` queries across Python compilation (`Query` assembly plus `SQLCompiler.as_sql`), raw SQLite cursor execution on the precompiled SQL, and full end-to-end execution. On a small in-memory table, building and compiling a correlated `Exists` takes `524.9 us` in Python while SQLite executes it in `19.0 us` — `89.7%` of the entire request is the ORM compiler.*

## Walking the compiler from top to bottom

Every query against `"desk/"`'s newsroom schema passes through the same six boundaries:

First, boolean trees enter as `Q` objects built on `Node` (`django/utils/tree.py:Node`), and `Query.add_q` (`django/db/models/sql/query.py:Query.add_q`) lowers them into a `WhereNode` tree capable of emulating `"XOR"`, partitioning `"WHERE"` from `"HAVING"` and `"QUALIFY"`, and folding empty predicates via `EmptyResultSet` (`django/core/exceptions.py:EmptyResultSet`) and `FullResultSet` (`django/core/exceptions.py:FullResultSet`). Second, every value-producing node — `F` (`django/db/models/expressions.py:F`), `Value` (`django/db/models/expressions.py:Value`), `CombinedExpression` (`django/db/models/expressions.py:CombinedExpression`), `Case` (`django/db/models/expressions.py:Case`), and `When` (`django/db/models/expressions.py:When`) — shares the `BaseExpression` contract, resolving symbolic field names into table-qualified `Col` (`django/db/models/expressions.py:Col`) nodes bound to concrete aliases. Third, double-underscore paths like `"published_at__year__gte"` are split into chains of `Transform` (`django/db/models/lookups.py:Transform`) nodes terminating in a `Lookup` (`django/db/models/lookups.py:Lookup`) dispatched through `RegisterLookupMixin` (`django/db/models/query_utils.py:RegisterLookupMixin`).

Beneath the predicates sits `Query` itself: an `"alias_map"` of `BaseTable` (`django/db/models/sql/datastructures.py:BaseTable`) and `Join` (`django/db/models/sql/datastructures.py:Join`) entries governed by reference counts (`"alias_refcount"`), join trimming (`Query.trim_joins`), `JoinPromoter` (`django/db/models/sql/query.py:JoinPromoter`), and `Query.split_exclude`. When rows are finally requested, `SQLCompiler.as_sql` walks the finished `Query`, dispatches vendor-specific `"as_<vendor>"` hooks through `SQLCompiler.compile` (`django/db/models/sql/compiler.py:SQLCompiler.compile`), keeps every user value inside the separate `"params"` tuple for parameter binding, and runs `BaseDatabaseOperations.get_db_converters` (`django/db/backends/base/operations.py:BaseDatabaseOperations.get_db_converters`) over every raw row returning from the cursor. Finally, aggregates, `Subquery` (`django/db/models/expressions.py:Subquery`), `OuterRef` (`django/db/models/expressions.py:OuterRef`), and `Window` (`django/db/models/expressions.py:Window`) bend the compiler's clause structure — wrapping queries in derived tables and guarding against Cartesian join fan-out.

We start at the top of the tree — how `Q` combines boolean predicates and lowers them into `WhereNode` — in [Q objects and the WhereNode tree](sql/q-and-where.md).
