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 Scanreads 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 ScanandBitmap Heap Scanuse an index. - Rows: estimate versus actual. A large mismatch means stale statistics (run
ANALYZE) or correlated columns. - Sort and filter nodes:
Rows Removed by Filtershows wasted reads; aSortnode 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 servesfilter(class_room=x).order_by("score")and, withLIMIT, 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 onclass_room_idwould always need the sort. - Partial index:
Index(fields=["roll_no"], condition=Q(active=True), name=...)for queries that always filteractive=True; smaller and faster to maintain. - Expression index:
Index(Lower("email"), name=...)is used byemail__iexactandannotate(Lower(...))comparisons. - Covering
include=[...](PostgreSQL) allows index-only scans. GinIndex/GistIndexfor 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.
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