Reiteach Aigean Logo
Reiteach Aigeanblog.reiteachaigean.com
Admin
HomeAI UpdatesCodingCloudApps & ToolsTech NewsArticles
postgresqldatabaseDjango17 min read·12 reads

PostgreSQL Composite Indexes with Django

Learn PostgreSQL composite indexes with Django: column order, leftmost prefix, partial and covering indexes, safe migrations, EXPLAIN ANALYZE, and common mistakes

S
Sizan Mahmud
Published on November 30, 2026
PostgreSQL Composite Indexes with Django

Introduction

A Django query that runs in 3 milliseconds on 20,000 rows can take several seconds on 20 million. In many cases, the fix is not a rewrite or a bigger server. It is one well-designed index.

A single-column index, like the one Django adds to every ForeignKey, helps simple lookups. But real queries rarely filter on just one column. They look like "this customer's orders, newest first" or "pending invoices for this tenant in the last 30 days". For queries like those, a composite index (also called a multi-column index) can be the difference between a fast, predictable query and a slow one that gets worse every month.

This guide explains how composite indexes work in PostgreSQL, how to define them in Django, how to choose the column order, and how to verify that your indexes are actually used. It also covers partial and covering indexes, safe migrations on large tables, and the mistakes that cost the most.

What Is a Composite Index?

A composite index is one index built over two or more columns. In PostgreSQL's default B-tree index, entries are sorted by the first column, then by the second column within each value of the first, and so on.

The classic analogy is a phone book sorted by last name, then first name. You can quickly find everyone named "Rahman". You can quickly find "Rahman, Karim". But you cannot quickly find everyone named "Karim" regardless of last name, because the book is not sorted that way.

That single idea explains almost every rule in this guide: the order of columns decides which queries the index can serve.

Why Not Just Add One Index Per Column?

You can, and PostgreSQL can sometimes combine separate indexes using a bitmap scan. But separate indexes have limits:

  • Combining two indexes means scanning both and merging bitmaps, which is more work than one targeted scan.
  • A single-column index cannot return rows already sorted by a second column, so the database may still sort a large result.
  • Two indexes cost more on writes than one, because both must be updated on every insert.

A composite index lets PostgreSQL walk straight to the matching range, read rows in the order you asked for, and often stop early when you use LIMIT.

Defining Composite Indexes in Django

You define indexes in the model's Meta class. Here is a typical orders table:

from django.db import models

class Order(models.Model):
    tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
    customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
    status = models.CharField(max_length=20)
    total = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(
                fields=["customer", "-created_at"],
                name="order_cust_created_idx",
            ),
        ]

Then generate and run the migration:

python manage.py makemigrations
python manage.py migrate

Details worth knowing:

  • Order of fields is the order of columns in the index.
  • A leading - means descending order for that column. That matters when your query sorts that way.
  • Index names are limited to 30 characters. Use a consistent pattern such as <model>_<cols>_idx.
  • index_together is gone. It was deprecated for years and removed in Django 5.1. Use Meta.indexes instead.

The SQL Django runs is roughly:

CREATE INDEX "order_cust_created_idx"
ON "orders_order" ("customer_id", "created_at" DESC);

The Leftmost Prefix Rule

Given an index on (a, b, c), a B-tree index is efficient for conditions that use the leading columns in order:

Query filters on Efficient with index (a, b, c)?
a Yes
a, b Yes
a, b, c Yes
b only Usually not
c only Usually not
a and c (skipping b) Only the a part narrows the search well

PostgreSQL can still use an index when the leading column is missing, but it may have to read a large portion of the index, which is often no better than a table scan. PostgreSQL 18 added skip scan for B-tree indexes, which helps in some cases where the leading column has few distinct values. Treat that as a bonus, and do not design around it.

In Django terms, with the index on ["customer", "-created_at"]:

## Uses the index well
Order.objects.filter(customer_id=42)
Order.objects.filter(customer_id=42).order_by("-created_at")[:20]

## Does NOT use it well: the leading column is missing
Order.objects.filter(created_at__gte=cutoff)

If you also run the second query often, it needs its own index starting with created_at.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

How to Choose Column Order

Column order is the most important decision, and a few practical rules cover most cases.

Rule 1: Equality columns first, range column last. Columns compared with = should come before a column compared with >, <, BETWEEN, or used for sorting.

## Query
Order.objects.filter(tenant_id=7, status="paid", created_at__gte=start)

## Good index: equality, equality, range
models.Index(fields=["tenant", "status", "created_at"])

Why? Once PostgreSQL hits a range condition, the entries after it are no longer in a single contiguous order for the next column, so columns placed after a range column help much less.

Rule 2: Put the sort column after the equality columns. If you filter by equality and sort by another column, the index can return rows already sorted, with no extra sort step.

## Query: recent orders for one customer
Order.objects.filter(customer_id=42).order_by("-created_at")[:20]

## Index: equality column, then sort column
models.Index(fields=["customer", "-created_at"])

With a LIMIT 20, PostgreSQL reads 20 index entries and stops. That is why this pattern scales so well.

Rule 3: Match the sort direction. PostgreSQL can scan a B-tree backward, so (customer, created_at) can serve ORDER BY created_at DESC for a single customer. Direction matters most when you sort by several columns in mixed directions, such as ORDER BY a ASC, b DESC. For that case, define the index with matching directions: fields=["a", "-b"].

Rule 4: Selectivity is not the first rule. A popular piece of advice says "put the most selective column first". It is a weak tiebreaker, not a rule. Query shape comes first. If every query filters by tenant_id, that column leads, even if it has few distinct values, because it makes every query's range contiguous.

Rule 5: Serve your real queries. Look at the queries your application actually runs, not the ones you imagine. One index per important query pattern beats a pile of speculative ones.

Keep Composite Indexes Narrow

More columns is not better. Each extra column makes the index larger and slower to maintain, and each column after the first helps fewer queries. Two to four columns covers most real cases. If you find yourself listing seven columns, you are probably trying to serve several different queries with one index, and splitting it will work better.

A Multi-Tenant Example

SaaS applications that store many customers' data in shared tables almost always filter by tenant first. In that case the tenant column should lead nearly every composite index:

class Invoice(models.Model):
    tenant = models.ForeignKey("Tenant", on_delete=models.CASCADE)
    status = models.CharField(max_length=20)
    due_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [
            models.Index(fields=["tenant", "status", "due_date"], name="inv_tenant_status_due_idx"),
            models.Index(fields=["tenant", "-created_at"], name="inv_tenant_created_idx"),
        ]
        constraints = [
            models.UniqueConstraint(fields=["tenant", "number"], name="inv_unique_tenant_number"),
        ]

The first index serves "overdue invoices for this tenant". The second serves "latest invoices for this tenant". The unique constraint enforces that invoice numbers are unique per tenant, and as a side effect it creates a composite unique index you can also query through.

Composite Unique Constraints

Uniqueness across a combination of columns is a composite index too, and it should be defined with UniqueConstraint, which is Django's recommended way:

class Meta:
    constraints = [
        models.UniqueConstraint(
            fields=["tenant", "slug"],
            name="uniq_tenant_slug",
        ),
    ]

This guarantees at the database level that no two rows share the same tenant and slug. It is also what makes get_or_create() safe under concurrency, and it is the safety net behind idempotent background tasks, which I cover in the related reading section.

Two useful options: condition=Q(...) makes the uniqueness apply only to some rows (a partial unique index), and in Django 5.0 and later with PostgreSQL 15 or newer, nulls_distinct=False treats NULLs as equal for uniqueness.

Covering Indexes with include

Normally, even when PostgreSQL finds a row through an index, it must visit the table (the "heap") to fetch the other columns you selected. A covering index stores extra columns inside the index, so a query can be answered from the index alone. PostgreSQL calls this an index-only scan.

Django supports this with the include argument:

models.Index(
    fields=["customer", "-created_at"],
    include=["status", "total"],
    name="order_cust_created_cov_idx",
)

This produces an index with INCLUDE (status, total). A query like this can then be served without touching the table:

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

Order.objects.filter(customer_id=42).order_by("-created_at").values("created_at", "status", "total")[:20]

Things to know before you use it:

  • Included columns are not part of the search order. They only ride along as payload.
  • They make the index larger. Include only a few small columns that the hot query really needs.
  • Index-only scans depend on PostgreSQL's visibility map, which autovacuum maintains. On tables with heavy updates, the benefit shrinks if vacuuming falls behind.
  • This needs PostgreSQL 11 or newer, and a Django version that supports include (3.2 and up).

Partial Indexes

A partial index covers only the rows that match a condition. If your queries mostly touch a small subset, such as unpaid or active rows, a partial index can be dramatically smaller and faster than a full one.

from django.db.models import Q

models.Index(
    fields=["tenant", "created_at"],
    condition=Q(status="pending"),
    name="order_pending_tenant_created_idx",
)

This indexes only pending orders. If 2% of your orders are pending, the index is a fraction of the size, which means less memory use and faster writes for all the rows that are not pending.

The catch: PostgreSQL only uses a partial index when it can prove your query's conditions imply the index condition. The query must include the same condition:

## Can use the partial index
Order.objects.filter(tenant_id=7, status="pending").order_by("created_at")

## Cannot use it: no status condition
Order.objects.filter(tenant_id=7).order_by("created_at")

Keep conditions simple and literal, and check with EXPLAIN that the planner picks the index.

Expression Indexes

If your query applies a function to a column, a normal index on that column cannot be used. A common example is case-insensitive search:

User.objects.filter(email__iexact="Sara@Example.com")

PostgreSQL evaluates UPPER("email") for this lookup, so a plain index on email does not help. Index the expression instead:

from django.db.models import F
from django.db.models.functions import Lower

class Meta:
    indexes = [
        models.Index(Lower("email"), name="user_email_lower_idx"),
    ]

Match the expression your query actually uses: an index on Lower("email") serves Lower("email") comparisons, and an iexact lookup uses UPPER, so check the generated SQL with print(qs.query) and build the index on the same expression. Note that Django does not allow mixing fields and expressions in one Index. To combine a plain column with an expression, use F() for the plain one:

models.Index(F("country"), Lower("last_name"), name="person_country_lastname_idx")

Remember that LIKE '%term%' (Django's icontains) cannot use a B-tree index at all because of the leading wildcard. For that, look at PostgreSQL trigram indexes with pg_trgm, which are a different index type.

Verify With EXPLAIN ANALYZE

Never trust an index until you have seen the plan. Django can run EXPLAIN for you:

qs = Order.objects.filter(customer_id=42).order_by("-created_at")[:20]
print(qs.explain(analyze=True, buffers=True))

Here is how to read the result:

  • Index Scan or Index Only Scan using your index is what you want. For a query with LIMIT, you should see it stop after reading a few rows.
  • Seq Scan on a large table means no usable index, or the planner decided a scan was cheaper. On a small table, a sequential scan is often the correct choice.
  • Sort nodes with large row counts suggest the index does not match your ORDER BY.
  • Bitmap Heap Scan is fine for medium-sized result sets, and it often means PostgreSQL combined several conditions.
  • Rows removed by filter that is large compared to rows returned means the index is not narrowing the search enough, and a better composite index may help.

Test with realistic data volumes. On a tiny development database, PostgreSQL will often ignore your index because scanning the table is cheaper. Use a copy of production data, or generate enough rows to match.

Also remember that the planner relies on statistics. After large data loads, run ANALYZE. If two columns are strongly correlated, such as country and city, the planner can badly misestimate row counts, and extended statistics (CREATE STATISTICS, run through a RunSQL migration) can help.

Check Which Indexes Are Actually Used

Indexes you never use still cost you on every write. PostgreSQL tracks usage:

SELECT relname AS table_name,
       indexrelname AS index_name,
       idx_scan,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC, pg_relation_size(indexrelid) DESC;

Indexes with idx_scan of zero over a long, representative period are candidates for removal. Be careful: counters reset when statistics are reset, indexes that enforce unique constraints must stay even if never scanned, and some indexes only serve rare but important jobs such as month-end reports. Check usage over a full business cycle before dropping anything.

Redundant Indexes

Django automatically creates an index on every ForeignKey. If you add a composite index that starts with that same column, the single-column index becomes mostly redundant, because the composite index can serve the same lookups through its leading column.

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

class Order(models.Model):
    customer = models.ForeignKey("Customer", on_delete=models.CASCADE, db_index=False)

    class Meta:
        indexes = [
            models.Index(fields=["customer", "-created_at"], name="order_cust_created_idx"),
        ]

Setting db_index=False on the foreign key removes the automatic single-column index. Do this only when you are sure the composite index covers every query that filters by that column, and when joins and cascading deletes still have an index to use. The composite index with customer as the leading column does serve those.

Add Indexes Safely on Large Tables

A normal CREATE INDEX blocks writes to the table while it builds. On a big production table, that can mean minutes of failed inserts. PostgreSQL has CREATE INDEX CONCURRENTLY, which builds the index without blocking writes, and Django exposes it through django.contrib.postgres.operations:

## orders/migrations/0008_order_cust_created_idx.py
from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import migrations, models

class Migration(migrations.Migration):
    atomic = False  # required for CONCURRENTLY

    dependencies = [
        ("orders", "0007_previous_migration"),
    ]

    operations = [
        AddIndexConcurrently(
            model_name="order",
            index=models.Index(
                fields=["customer", "-created_at"],
                name="order_cust_created_idx",
            ),
        ),
    ]

Points to remember:

  • atomic = False is required. CONCURRENTLY cannot run inside a transaction block.
  • Keep the migration small. Put the concurrent index operation alone in its migration, so a failure does not leave the rest half-applied.
  • A failed build leaves an invalid index. If the build is interrupted, PostgreSQL leaves an INVALID index behind. Drop it and run again. Use RemoveIndexConcurrently or DROP INDEX CONCURRENTLY.
  • It takes longer and uses more resources than a normal build, and it still adds I/O load, so run it off-peak.
  • Use RemoveIndexConcurrently for removal on big tables too.

The Cost Side: Writes, Space, and Bloat

Indexes speed up reads and slow down writes. Every INSERT updates every index on the table. Every UPDATE that changes an indexed column must update the index entries as well, and it can prevent PostgreSQL's heap-only tuple (HOT) optimization, which makes updates cheaper. Indexes also take disk space and compete for memory in the cache.

Practical guidelines:

  • Index what your queries need, not everything.
  • On write-heavy tables, keep the index count low and the indexes narrow.
  • Avoid indexing columns that are updated constantly, such as a frequently changing last_seen timestamp, unless you really need to search on them.
  • Monitor index size over time, and rebuild bloated indexes with REINDEX CONCURRENTLY when needed.

Common Mistakes to Avoid

  1. Wrong column order. An index on (created_at, customer) does not help WHERE customer_id = 42. Equality columns come first.
  2. Putting a range column before equality columns. The columns after a range condition help far less.
  3. Indexing every column "just in case". It slows writes and wastes space.
  4. Testing on tiny data. The planner skips indexes on small tables.
  5. Forgetting the sort. A filter index that does not match ORDER BY still leaves an expensive sort.
  6. Partial index without the matching condition in the query. PostgreSQL will not use it.
  7. Applying functions to indexed columns (Lower, date casts, arithmetic) without an expression index.
  8. Leading-wildcard searches with icontains on a B-tree index.
  9. Adding indexes without checking usage later. Unused indexes only cost you.
  10. Blocking migrations on large tables. Use AddIndexConcurrently.
  11. Ignoring ANALYZE. Stale statistics lead to bad plans even with good indexes.

Quick Reference: Which Index for Which Query?

Query pattern Suggested index
Filter by one column, sort by another, LIMIT ["filter_col", "-sort_col"]
Several equality filters plus a date range ["a", "b", "date_col"]
Mostly querying a small subset (for example pending rows) Partial index with condition
Read-heavy query returning few columns Composite index with include
Case-insensitive lookup Expression index such as Lower("email")
Unique per tenant UniqueConstraint(fields=["tenant", "slug"])
Keyset pagination by time ["-created_at", "-id"]
Multi-tenant list screens Tenant column first in every composite index

Related Reading: Indexes Are One Part of a Fast Django Stack

A good index only pays off when the rest of your queries and jobs are healthy too. These guides cover the neighbors:

A Practical Checklist

Before adding a composite index, confirm that you:

  • Found the slow query with Debug Toolbar, slow query logs, or EXPLAIN ANALYZE
  • Wrote down the exact filter, sort, and LIMIT the query uses
  • Put equality columns first, then the sort or range column
  • Matched sort directions for mixed ORDER BY queries
  • Kept the index to roughly two to four columns
  • Considered a partial index if you only query a small subset
  • Considered include for a hot, read-heavy query
  • Used an expression index if the query applies a function to a column
  • Checked that a new composite index does not make an older one redundant
  • Created it with AddIndexConcurrently on large production tables
  • Tested with realistic data and confirmed the new plan with EXPLAIN ANALYZE
  • Reviewed pg_stat_user_indexes later to confirm it is used and to find unused ones

Conclusion

Composite indexes are one of the highest-return tools in a Django and PostgreSQL stack, and one of the easiest to get subtly wrong. The core idea is simple: a B-tree index is sorted by its first column, then its second, and so on, so the order of columns decides which queries it can serve. Put equality columns first, follow with the sort or range column, keep the index narrow, and match it to a real query.

Then verify. Read the plan, test on realistic data, add indexes concurrently on big tables, and review usage over time so you pay for the indexes that earn their keep. Do that consistently, and your queries stay fast as your tables grow from thousands of rows to millions.

Frequently Asked Questions

What is a composite index in Django? A composite index is an index over multiple columns. In Django you define one with models.Index(fields=["col_a", "col_b"]) inside Meta.indexes. PostgreSQL sorts the index by the first column, then the second, so it can speed up queries that filter or sort on those columns in that order.

Does the column order matter in a PostgreSQL composite index? Yes, it is the most important decision. A B-tree index on (a, b) serves queries on a, or on a and b, efficiently, but generally not queries on b alone. Put columns compared with equality first, and the sort or range column last.

What is the leftmost prefix rule? It means an index on (a, b, c) is efficient for conditions starting from the leftmost columns: a, then a, b, then a, b, c. Conditions that skip the leading column usually cannot use the index efficiently, although PostgreSQL 18 added skip scan, which helps in some cases.

What replaced index_together in Django? Meta.indexes with models.Index(fields=[...]). index_together was deprecated and removed in Django 5.1. For uniqueness across several columns, use UniqueConstraint(fields=[...]).

How do I add an index in Django without locking the table? Use AddIndexConcurrently from django.contrib.postgres.operations and set atomic = False on the migration. It builds the index with CREATE INDEX CONCURRENTLY, which does not block writes. If a build fails, drop the invalid index and try again.

What is a covering index and how do I create one in Django? A covering index stores extra columns in the index so a query can be answered by an index-only scan without visiting the table. In Django, pass include=[...] to models.Index. It requires PostgreSQL 11 or newer, and it works best on tables that are vacuumed regularly.

Why does PostgreSQL ignore my index? Common reasons are a table too small for an index to be worth it, a query that does not match the index's leading columns, a function applied to the indexed column, a partial index whose condition is not in the query, or stale statistics. Check the plan with explain(analyze=True) and run ANALYZE if needed.

How many indexes are too many? There is no fixed number, but every index slows writes and uses space and memory. Keep only the indexes that serve real queries, and review pg_stat_user_indexes periodically to find ones that are never used.

Share this article

Pass this technical dispatch along to fellow engineers

Did you enjoy this article?

Rate it so we know what content to bring next

Comments (0)