Django 6.1.3

8.6 From Python to SQL

SQLCompiler.as_sql and parameter binding

In what exact order does SQLCompiler.as_sql 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.get_compiler asks the active database backend’s operations class (BaseDatabaseOperations.compiler) 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.as_sql 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.as_sql snapshots "alias_refcount" (so its "finally" block can roll back any temporary compilation joins via Query.reset_refcounts), and executes two strict phases:

  1. Setup phase (SQLCompiler.pre_sql_setup, lines 82–96):
    • SQLCompiler.setup_query ensures an initial base-table alias exists and calls SQLCompiler.get_select, expanding get_default_columns, select_related trees (get_related_selections), and annotations into (expr, (sql, params), alias) tuples.
    • SQLCompiler.get_order_by resolves ordering expressions (which may add joins via find_ordering_name).
    • WhereNode.split_having_qualify partitions Query.where into "self.where", "self.having", and "self.qualify".
    • SQLCompiler.get_extra_select and SQLCompiler.get_group_by compute any auxiliary "SELECT" columns and minimal "GROUP BY" expressions (including SQLCompiler.collapse_group_by primary-key reduction when supported by the backend).
  2. Emission phase (SQLCompiler.as_sql, lines 794–997):
    • If the query uses a set combinator ("UNION", "INTERSECT", "EXCEPT"), get_combinator_sql compiles the child queries instead.
    • Else if "self.qualify" is non-empty (filtering on a Window expression), SQLCompiler.get_qualify_sql wraps the inner query in a derived table.
    • Otherwise as_sql calls get_distinct(), then only after every join-adding clause has run, calls SQLCompiler.get_from_clause, compiles "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".

Every individual AST node along the way passes through SQLCompiler.compile — a seven-line dispatcher that looks up "as_<connection.vendor>" ("as_sqlite", "as_postgresql", "as_mysql", "as_oracle") on the node before falling back to BaseExpression.as_sql. 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.as_sql: (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.execute, CursorWrapper.execute, called inside SQLCompiler.execute_sql, SQLCompiler.execute_sql). 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.convert_query rewrites unescaped "%s" placeholders into "?" right before calling C-level sqlite3.Cursor.execute.

Watch a classic SQL injection payload pass through SQLCompiler.as_sql, SQLiteCursorWrapper.convert_query, and SQLCompiler.execute_sql on "desk/", alongside Django’s row-decoding converters:

Recorded on Django 6.1.3 ch08-sql script
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.execute or RawSQL; always inspect Query.sql_with_params to see the true wire boundary.

The return trip: results_iter and field converters

After SQLCompiler.execute_sql streams batches of raw tuples out of cursor_iter, SQLCompiler.results_iter transforms database driver values back into Python domain objects using field converters.

For each selected expression, SQLCompiler.get_converters collects two converter lists and concatenates them in order: first BaseDatabaseOperations.get_db_converters for backend-specific decoding, then Field.get_db_converters (Field.get_db_converters, 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.apply_converters 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.convert_datetimefield_value — which attaches datetime.timezone.utc 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.composite_fields_to_tuples.)

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.as_sql), raw SQLite execution of the precompiled SQL, and full end-to-end execution:

Recorded on Django 6.1.3 ch08-bench script
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.