← Back to Django, page 5

django-0089 · Hard senior

How do you read QuerySet.explain() output on PostgreSQL and choose indexes (B-tree, partial, composite, functional) based on the plan?

QuerySet.explain(analyze=True) runs EXPLAIN against the SQL Django generates. Look at the scan node (Seq Scan versus Index Scan or Bitmap Heap Scan), estimated versus actual rows, loops and time. Choose a B-tree index whose leading columns match equality filters then the sort, a partial index for a common subset, an expression index for functions like LOWER(), and always re-check the plan after creating it, with fresh statistics (ANALYZE).

Full answer

str(qs.query) shows SQL; qs.explain() shows how the database will execute it. explain(analyze=True) actually runs the query (do not use it on writes in production) and adds real timings.

What to read:

  • Scan type: Seq Scan reads the whole table. That is fine for tiny tables or when most rows are returned, and bad for selective filters on large tables. Index Scan, Index Only Scan and Bitmap Heap Scan use an index.
  • Rows: estimate versus actual. A large mismatch means stale statistics (run ANALYZE) or correlated columns.
  • Sort and filter nodes: Rows Removed by Filter shows wasted reads; a Sort node suggests an index could provide the order.
  • Time and loops: nested loops over many rows indicate N+1-like plans inside the query.

Index choices:

  • Composite (class_room_id, score): equality columns first, range or sort column last. It serves filter(class_room=x).order_by("score") and, with LIMIT, lets the database read the first rows in index order and skip the sort. When many rows match and no limit applies, the planner may still prefer a bitmap scan plus a sort, and that is a legitimate choice. A single-column index on class_room_id would always need the sort.
  • Partial index: Index(fields=["roll_no"], condition=Q(active=True), name=...) for queries that always filter active=True; smaller and faster to maintain.
  • Expression index: Index(Lower("email"), name=...) is used by email__iexact and annotate(Lower(...)) comparisons.
  • Covering include=[...] (PostgreSQL) allows index-only scans.
  • GinIndex/GistIndex for JSON, arrays, full text and trigram search.
  • Create indexes on busy tables with AddIndexConcurrently (non-atomic migration).

Costs: every index slows writes and uses space. Remove unused indexes (check pg_stat_user_indexes). Test on realistic row counts, because plans on small tables differ. The planner may legitimately ignore an index; do not force it, understand why.

python
import os
import sys
import types

import django
from django.conf import settings

sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get("PGDATABASE", "school"),
        "USER": os.environ.get("PGUSER", "postgres"),
        "PASSWORD": os.environ.get("PGPASSWORD", ""),
        "HOST": os.environ.get("PGHOST", "localhost"),
        "PORT": os.environ.get("PGPORT", "5432"),
    }},
)
django.setup()

from django.db import models, connection


class Fee(models.Model):
    class_room = models.IntegerField()
    score = models.IntegerField()
    active = models.BooleanField(default=True)

    class Meta:
        app_label = "school"


with connection.cursor() as cur:
    cur.execute("DROP TABLE IF EXISTS school_fee")
with connection.schema_editor() as editor:
    editor.create_model(Fee)

Fee.objects.bulk_create([Fee(class_room=i % 500, score=i % 97, active=(i % 50 == 0)) for i in range(60000)], batch_size=5000)


def plan(qs):
    return qs.explain()


def scan_kind(text):
    for kind in ("Index Only Scan", "Bitmap Heap Scan", "Index Scan", "Seq Scan"):   # check Bitmap first: "Bitmap Index Scan" contains "Index Scan"
        if kind in text:
            return kind


def analyze():
    with connection.cursor() as cur:
        cur.execute("ANALYZE school_fee")


query = Fee.objects.filter(class_room=42).order_by("score")
analyze()
print("without index:", scan_kind(plan(query)))

with connection.schema_editor() as editor:
    editor.add_index(Fee, models.Index(fields=["class_room", "score"], name="fee_room_score_idx"))
analyze()
text = plan(query)
print("composite index, all 120 matches:", scan_kind(text), "| sort node:", "Sort" in text)
text = plan(query[:5])
print("composite index, first 5 only:", scan_kind(text), "| sort node:", "Sort" in text)

partial = Fee.objects.filter(active=True, score=5)
with connection.schema_editor() as editor:
    editor.add_index(Fee, models.Index(fields=["score"], condition=models.Q(active=True), name="fee_active_score_idx"))
analyze()
print("partial index used:", "fee_active_score_idx" in plan(partial))
print("analyze shows actual time:", "actual time" in Fee.objects.filter(class_room=42).explain(analyze=True))

with connection.cursor() as cur:
    cur.execute("DROP TABLE school_fee")

Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): without index: Seq Scan composite index, all 120 matches: Bitmap Heap Scan | sort node: True composite index, first 5 only: Index Scan | sort node: False partial index used: True analyze shows actual time: True

Key points

  • explain() shows the plan; analyze=True runs it for real timings
  • Seq Scan versus Index Scan; compare estimated and actual rows
  • Composite index order: equality columns, then sort or range column
  • Partial and expression indexes match specific query shapes
  • Indexes cost writes; verify with ANALYZE and re-check plans

Common mistakes

  • Judging performance from SQL text alone without EXPLAIN
  • Running explain(analyze=True) on write statements in production
  • Putting the sort column before equality columns in a composite index
  • Adding indexes that are never used
  • Testing plans on tiny tables

Follow-ups

  • How do you create an index without blocking writes?
  • What does Index Only Scan need to work?
  • How would you find unused indexes?

Tips

  • Name scan types
  • Explain composite order
  • Mention ANALYZE and concurrent creation