Composite index

What it is

A composite index is a database index with more than one key column.
A PostgreSQL B-tree on tenant identifier and reading time can keep
rows arranged by tenant and then by time within each tenant. The
database can use this arrangement to find a particular tenant's
interval without reading every row in the table. Column order
matters because it shapes which parts of the index the database can
locate and scan efficiently.

A dashboard request for readings from one tenant during a time
interval fits that ordering. Equality on the tenant selects one
region of the index and the time range narrows the scan within it. A
query for all tenants during the same interval has a different
shape. The database may have to visit many separate regions.
PostgreSQL can sometimes use a skip scan on a multicolumn B-tree if
the planner judges it beneficial, but that depends on the
distribution and available alternatives. Test the actual query and
data before relying on that choice.

Index definitions can contain key columns that determine ordering as
well as extra columns stored so that the index can provide other
values. PostgreSQL supports INCLUDE columns for eligible index
types. These values can help an index-only scan when the visibility
information also makes that possible. They have different semantics
from key columns. A unique composite key enforces uniqueness of the
combination under the engine's rules. If code expects to find each
component on its own, check that it actually has a separately useful
index or access path.

Why it matters

A suitable index can reduce page reads and sorting for common access
patterns. The effect is greatest when index order and the query
agree about what narrows the result or permits an early stop. A
dashboard that fetches twenty recent readings from one tenant can
often stop after finding enough candidates if the index gives them
in the needed order. A monthly export may need most rows in a
partition and benefit differently. Inspect both with representative
parameters.

Additional indexes also add storage and work to inserts, updates and
deletes. An index with wider keys or included values can become
expensive on a table that receives many writes. It can increase the
amount of data to maintain and hold in memory. Decide which request
or job needs improvement and collect both read and write
measurements. A faster query that is rarely called may be less
valuable than a smaller index with strong benefits for several
popular routes.

Column order is a design choice about the workload. Equality
predicates, range predicates, join keys and requested ordering all
matter. For separately queried columns, multiple single-column
indexes may be useful and the database may be able to combine them
for some queries. A composite index can serve an ordered lookup
particularly well. Compare the alternatives on the real sizes and
distributions, and allow for changes in the most frequent query
shapes as the product grows.

What it looks like in practice

Suppose a readings table stores a tenant, a device, a time and a
value. Collect common queries from the dashboard before creating an
index. Compare a single tenant's latest readings with a fleet report
across tenants, an individual device drill-down and a broad export.
Record which columns are filtered by equality, which use ranges and
how the result is ordered. Use a sample large enough to show useful
differences between one heavily used tenant and many lightly used
ones.

Try the proposed tenant and reading-time index in a safe test
environment. Compare plans and end-to-end elapsed time before and
after. Include the effect during sustained ingest. A plan shows the
rows produced by the index scan and whether subsequent row visits or
sorting still account for most of the work. Buffer counters add
evidence about the pages accessed. Confirm that any improvement
persists for the query groups you selected. If a later condition is
selective but almost every page must be visited first, reconsider
the key order, query or layout.

Our PostgreSQL optimisation case study describes adding composite
indexes for filters such as tenant ID plus a date range for
electrical data. It also describes partitioning and query rewrites,
so the overall result reflects several changes. The readings example
isolates an index decision and gives a way to measure how much of
that specific workload it helps.

Where it goes wrong

An index can match a query's list of columns without matching how
the query uses them. A function on a filtered column, incompatible
type coercion or a different collation can change the available
access paths. Sort direction and null ordering matter for some
ordered scans. Check the exact expression and plan seen in
production. A different expression index, key ordering or query
shape may be necessary.

A wide covering index can look attractive in a mostly read-only test
and be costly in operation. Measure disk, cache pressure and update
cost. Validate indexes under the table's actual churn because
PostgreSQL may need heap visits for visibility checks even when an
index carries every requested column. Add included fields only for
reads whose measured benefit justifies the larger structure.

Multiple near-identical indexes can accumulate as features change.
Find which queries and constraints use an index before dropping or
replacing it. Confirm that a proposed replacement supports common
leading-column lookups and the uniqueness rules the old one
enforced. Use the database's documented build and replacement
procedure, observe its lock and storage demands, and define how to
stop if the operation threatens normal traffic.

Further reading

  * PostgreSQL multicolumn indexes explains column order, qualifying
conditions and skip scans.

  * PostgreSQL indexes and ordering describes when a B-tree can
provide the order a query requests.

  * PostgreSQL covering indexes covers included columns and the
visibility requirements for index-only scans.

hThis page on the web	URL:https://engineer.company/glossary/composite-index/	engineer.company	70
