SQLCompiler.as_sql and parameter binding
In what exact order does SQLCompiler assemble SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT clauses, and why are values never interpolated into the SQL string?
When a QuerySet finally demands rows, Query asks the active database backend’s operations class (BaseDatabaseOperations) for its compiler class — SQLCompiler for "SELECT" queries (with sibling subclasses SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler, and SQLAggregateCompiler).
The exact assembly order inside SQLCompiler.as_sql
A common mistake when reading SQLCompiler is assuming it builds SQL clauses in the order they appear in the final text. It cannot — because "ORDER BY" and "DISTINCT ON" can introduce new joins into Query.alias_map that must already exist before "FROM" is emitted!
Instead, SQLCompiler snapshots "alias_refcount" (so its "finally" block can roll back any temporary compilation joins via Query), and executes two strict phases:
- Setup phase (
SQLCompiler, lines 82–96):.pre_sql_setup SQLCompilerensures an initial base-table alias exists and calls.setup_query SQLCompiler, expanding.get_select get_default_columns,select_relatedtrees (get_related_selections), and annotations into(expr, (sql, params), alias)tuples.SQLCompilerresolves ordering expressions (which may add joins via.get_order_by find_ordering_name).WhereNodepartitions.split_having_qualify Query.whereinto"self.where","self.having", and"self.qualify".SQLCompilerand.get_extra_select SQLCompilercompute any auxiliary.get_group_by "SELECT"columns and minimal"GROUP BY"expressions (includingSQLCompilerprimary-key reduction when supported by the backend)..collapse_group_by
- Emission phase (
SQLCompiler, lines 794–997):.as_sql - If the query uses a set combinator (
"UNION","INTERSECT","EXCEPT"),get_combinator_sqlcompiles the child queries instead. - Else if
"self.qualify"is non-empty (filtering on aWindowexpression),SQLCompilerwraps the inner query in a derived table..get_qualify_sql - Otherwise
as_sqlcallsget_distinct(), then only after every join-adding clause has run, callsSQLCompiler, compiles.get_from_clause "self.where"and"self.having", and concatenates the fragments in strict SQL wire order while appending each clause’s parameter list in matching left-to-right order:"SELECT","DISTINCT", select columns,"FROM"+"JOIN"s,"WHERE","GROUP BY","HAVING","ORDER BY","LIMIT"/"OFFSET", and"FOR UPDATE".
- If the query uses a set combinator (
Every individual AST node along the way passes through SQLCompiler — a seven-line dispatcher that looks up "as_<connection ("as_sqlite", "as_postgresql", "as_mysql", "as_oracle") on the node before falling back to BaseExpression. That single lookup is how one vendor-neutral Query tree emits SQLite "CAST(... AS REAL)" on one connection and PostgreSQL native syntax on another.
Parameter binding: why hostile strings can never become SQL syntax
Look at the return type of SQLCompiler: (sql, tuple(params)). Across every Lookup, Value, and WhereNode, user data is never formatted into the "sql" string via Python string interpolation. Every literal value emits the placeholder "%s" into "sql" and appends the raw Python value to "params".
That separation — parameter binding — holds all the way to the database driver’s wire protocol (CursorWrapper, CursorWrapper, called inside SQLCompiler, SQLCompiler). Because PostgreSQL (psycopg), MySQL, and Oracle drivers understand "%s" natively while Python’s stdlib sqlite3 uses "?" ("qmark" style), Django’s SQLite backend wraps the cursor in SQLiteCursorWrapper, whose SQLiteCursorWrapper rewrites unescaped "%s" placeholders into "?" right before calling C-level sqlite3.
Watch a classic SQL injection payload pass through SQLCompiler, SQLiteCursorWrapper, and SQLCompiler on "desk/", alongside Django’s row-decoding converters:
6. SQLCompiler.as_sql, parameter binding, and field converters
hostile_input = "'; DROP TABLE newsroom_story; --"
compiler_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"."slug" = %s ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
compiler_params = ("'; DROP TABLE newsroom_story; --",)
sqlite_converted_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"."slug" = ? ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC
executed_rows=0 queries=1 stories_remaining=6
converters_by_col = {2: ['DatabaseOperations.convert_datetimefield_value']}
raw_sqlite_col2 = datetime.datetime(2026, 11, 25, 10, 15) type=datetime
converted_col2 = datetime.datetime(2026, 11, 25, 10, 15, tzinfo=datetime.timezone.utc) type=datetime
One warning belongs right beside that recording: str(qs.query) executes sql % params purely for debugging readability without quoting strings! Never pass str(qs.query) to CursorWrapper or RawSQL; always inspect Query to see the true wire boundary.
The return trip: results_iter and field converters
After SQLCompiler streams batches of raw tuples out of cursor_iter, SQLCompiler transforms database driver values back into Python domain objects using field converters.
For each selected expression, SQLCompiler collects two converter lists and concatenates them in order: first BaseDatabaseOperations for backend-specific decoding, then Field (Field, which checks for and appends any custom "from_db_value" method on a Field subclass). Columns with no converters (such as "id", "slug", and "priority" above) are omitted from the dict completely, so SQLCompiler touches only the columns that actually need work.
Look at lines 89–91 of the recording above: for ("id", "slug", "published_at", "priority"), only column index 2 ("published_at") registers a converter — DatabaseOperations — which attaches datetime onto the naive datetime returned by SQLite! (And if a query selects composite fields represented by ColPairs, results_iter folds their slices back into Python tuples via SQLCompiler.)
What SQLCompiler actually costs on the clock
Before assuming your database is the bottleneck on simple queries, look at our apples-to-apples benchmark from ch08-bench comparing identical "values_list('id', flat=True)" queries across Python compilation (Query assembly plus SQLCompiler), raw SQLite execution of the precompiled SQL, and full end-to-end execution:
1. Python Query+as_sql() vs total execution vs raw SQLite (7 trials, us/query)
shape compile_us sqlite_us total_us compile_pct sql_chars
simple_filter 184.6 19.1 244.0 75.7% 143
two_fk_joins 281.0 21.1 346.5 81.1% 354
m2m_chained_2_aliases 342.0 23.0 402.4 85.0% 427
correlated_exists 524.9 19.0 585.5 89.7% 225
window_qualify 729.9 34.9 900.5 81.0% 397
Look at those ratios: every time an N+1 loop fires a fresh QuerySet, you are not just paying database I/O — you are paying 185 us to 730 us of Python AST compilation per query, 76% to 90% of total wall-clock time on a fast local query! And notice why "correlated_exists" (524.9 us) and "window_qualify" (729.9 us) cost three to four times as much to compile as "simple_filter" (184.6 us): nested queries and window filters reshape the entire "SELECT" structure. We open aggregates, subqueries, and windows next in Aggregates, annotations, subqueries, and windows.