Data · L1Secondary, composite and special indexes

Secondary, composite and special indexes

Pick indexes that match your real queries, read the plan to prove it, and count what every extra index costs on writes.

L1 Must-knowData24 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

What broke

On 6 January 2026, GitLab.com slowed down for 2 hours and 36 minutes. Merge requests were slow and CI pipelines started late. Customers opened emergency tickets. 1

A background job queue grew to between 600,000 and 700,000 jobs. The PgBouncer connection pool in front of the primary database was 100% full from 07:12 UTC. Database CPU stayed high. 1

The cause was one missing index. A migration after a deploy had removed index_ssh_signatures_on_commit_sha. That was a single-column index on ssh_signatures (commit_sha). 1

Queries that looked up signatures by commit_sha became slow or timed out. They held connections for longer, so the pool filled up, and everything else waited. By 08:51 the team had found the cause and recreated the index by hand. Performance came back. 1

One follow-up is the lesson of this page. GitLab updated its docs on the column order of composite indexes. The point: a query that uses only the trailing columns of a composite index is not covered by it. 1

The review does not say why the index looked safe to drop. But here is the lesson for you. An index can look like a copy of another one. It can still be the only one that serves a query.

Section 2 of 8

The idea in simple words

A table stores its rows in one way. InnoDB keeps them sorted by primary key. Postgres keeps them in no particular order. A secondary index is an extra sorted copy of a few columns, with a pointer back to each row. It lets the database find rows by something other than the main key, like orders by customer.

In PostgreSQL, every index is a secondary index. The rows live in a separate area called the heap. A normal index scan reads the index, then fetches each row from the heap. 2

MySQL's InnoDB works differently. The primary key index (the clustered index) holds the rows themselves. Each secondary index entry stores the row's primary key. So a lookup finds the primary key first, then searches the clustered index for the row. 3 That is why InnoDB advises a short primary key: it is copied into every secondary index. 3

The key idea. An index is a promise to answer one shape of query fast. You pay for that promise on every write. Choose indexes from your real queries, check the plan, and remove the ones nothing needs.

You already know how a B-tree stores sorted keys from the B-tree and LSM lesson. This lesson is about which keys to put in it.

Section 3 of 8

How it works

Step through one composite index and three queries. Use Next and Back, or the ← and → keys.

One index on (customer_id, created_at): a fast range, a query it cannot help, and a covering indexIndex on (customer_id, created_at) 7May 17May 942May 242May 642May 958May 8sorted by customer, then by date A · customer 42, since May 67May 17May 942May 242May 642May 958May 8✓ one short range, side by side B · any customer, since May 67May 17May 942May 242May 642May 958May 8✗ matches are spread outno single range: often a full table scan A also needs status and total42May 642May 9table (heap)Index Scan:one table visit per row + INCLUDE (status, total)→ Index Only Scan SeniorPath
  1. The index keeps one entry per row, sorted by customer_id first. Inside one customer, entries are sorted by created_at. Each entry also points to its row in the table.
  2. Query A gives an exact customer and a start date. All its matches sit next to each other. The database jumps to the first one and reads until the range ends.
  3. Query B gives only a date. The dates are sorted only inside each customer, so the matches are spread across the whole index. The database usually reads the whole table instead.
  4. Query A also wants status and total. Those columns are not in the index. So for each match, Postgres must visit the table, called the heap, to read the row.
  5. Add the two columns with INCLUDE. Now the index holds everything A needs. Postgres can answer from the index alone, if the table pages are marked all-visible.
Step 1 of 5

Composite indexes and column order

A composite index sorts by its first column, then by the second inside each value of the first, and so on. Think of a phone book: sorted by last name, then first name.

PostgreSQL states the exact rule. Equality conditions on the leading columns, plus a range on the first column without equality, narrow the part of the index it reads. Conditions on later columns are only checked along the way. 4

So put equality columns first, then the range column. Winand shows the same with a date range and a subsidiary ID: with the equality column first, the scan reads far fewer index pages. 6

CREATE INDEX orders_customer_created_idx
  ON orders (customer_id, created_at);

-- Uses the index well: equality, then range
SELECT id FROM orders
WHERE customer_id = 42 AND created_at >= '2026-05-06';

-- Cannot narrow the scan: no condition on customer_id
SELECT id FROM orders WHERE created_at >= '2026-05-06';

PostgreSQL 18 can sometimes "skip scan" past a leading column with no equality condition. 5 It usually does this only when that column has few distinct values. With many values, the planner usually prefers a full table scan. 4 The docs also say to use multicolumn indexes sparingly. Indexes with more than three columns rarely help. 4

Covering indexes and index-only scans

If the index holds every column the query needs, Postgres can skip the heap. This is an index-only scan. 2 An index that holds every column a query needs is a covering index. You can add extra "payload" columns with INCLUDE. They are stored but are not part of the search key. 2

CREATE INDEX orders_customer_created_cov_idx
  ON orders (customer_id, created_at) INCLUDE (status, total);

There is a catch. Postgres must still check that each row is visible to your transaction. It skips the heap only for pages marked all-visible in the table's visibility map. 2 VACUUM updates that map. 13 On a table where many rows change, index-only scans may gain you little. Wide payload columns also make the index bigger. 2

Partial, expression and unique indexes

A partial index covers only rows that match a WHERE condition. 7 It is small when most rows don't matter, like unbilled orders. The query's condition must clearly match the index condition. A parameter like x < $1 does not count. 7

CREATE INDEX orders_unbilled_idx
  ON orders (created_at) WHERE billed = false;

An expression index stores the result of an expression. A search on lower(email) can use it. 8 The expression runs on each insert and on many updates, so writes cost more. Use one when fast reads matter more than fast writes. 8

CREATE UNIQUE INDEX users_email_lower_idx ON users (lower(email));

Because it is UNIQUE, this index also blocks two emails that differ only in case. 8 A unique constraint or primary key creates its unique index for you. Don't add a second one by hand. 9 By default, a unique index allows many nulls. NULLS NOT DISTINCT changes that. 9

Reading EXPLAIN

EXPLAIN shows the query plan. EXPLAIN ANALYZE also runs the query and shows real row counts and times. It really runs it, so wrap an UPDATE or DELETE in a transaction and end it with ROLLBACK. 10

The scan nodes you will see most:

  • Seq Scan: reads the whole table.
  • Index Scan: walks the index, then visits the heap for each row. 2
  • Index Only Scan: answers from the index, visiting the heap only for pages not marked all-visible. 2
  • Bitmap Index Scan + Bitmap Heap Scan: first collects matching row locations, sorts them into physical order, then reads the pages. It skips pages with no matches, so it can beat a full scan. 10

Here is a query that the covering index above can answer alone. Every column it uses is in the index.

EXPLAIN ANALYZE
SELECT status, total FROM orders
WHERE customer_id = 42 AND created_at >= '2026-05-06';

The plan below is illustrative: we made up the numbers, in the PostgreSQL 18 style. PostgreSQL 18 shows buffers by default and prints fractional row counts. 5 The long lines are wrapped to fit a phone.

Index Only Scan using orders_customer_created_cov_idx on orders
    (cost=0.43..8.61 rows=12 width=12)
    (actual time=0.031..0.044 rows=11.00 loops=1)
  Index Cond: ((customer_id = 42) AND
    (created_at >= '2026-05-06 00:00:00+00'::timestamp with time zone))
  Heap Fetches: 0
  Index Searches: 1
  Buffers: shared hit=4
Planning Time: 0.112 ms
Execution Time: 0.061 ms

Heap Fetches: 0 means no row needed a heap visit. A high number means many pages are not all-visible: rows changed recently, or VACUUM is behind. 2 Also look for Rows Removed by Filter: rows read and then thrown away. 10

What each index costs

The database must keep every index in step with the table. That adds work to each insert, update and delete. 11 Indexes also use disk and memory.

Postgres has a cheaper kind of update that skips index work. More indexes make it happen less often. 11 The docs say plainly: remove indexes that are seldom or never used. 11

To find them, look at pg_stat_user_indexes. Its idx_scan column counts scans, and last_idx_scan (PostgreSQL 16 and later) gives the time of the last one. 12

SELECT indexrelname, idx_scan, last_idx_scan
FROM pg_stat_user_indexes
ORDER BY idx_scan;

A unique index can show zero scans and still be needed, because it enforces the constraint. 9 Never drop one for a low idx_scan.

Counters reset after a crash or a restore from backup. Each server, including each replica, keeps its own counters. 12 A replica that serves reports may use an index the primary never touches. Dropping it on the primary removes it from the replicas too. So check every server first.

Building an index on a live table

A normal CREATE INDEX lets reads continue but blocks inserts, updates and deletes until it finishes. 14 On a large table, the build can take a long time. 11

CREATE INDEX CONCURRENTLY does not block writes, but it is slower and can leave an invalid index if it fails. 14 See schema migrations for how to ship this safely.

Special index types in one line each

  • GIN: an inverted index for values with many parts: arrays, jsonb and full text search. Fast to search, slow to update. 16 See search systems.
  • GiST: a framework for many index types, including geometric data and nearest-neighbour search ("the 10 closest shops"). 15
  • BRIN: tiny summaries per block range. Use it for huge tables where a column follows the physical row order, like an order date in an append-only table. 17
  • Hash: equality only. 15 A B-tree also handles equality, so start with a B-tree.

At scale: local and global secondary indexes

When data is split across machines, an index can be local to each piece, or global. The sharding lesson explains both. DynamoDB makes the trade-off concrete.

A local secondary index (LSI) keeps the table's partition key with a different sort key. It allows strongly consistent reads. But it must be created with the table, and all items with one partition key value, in the table and its local indexes together, are limited to 10 GB. 19

A global secondary index (GSI) can use any key. It is updated asynchronously, usually "within a fraction of a second", so reads may be out of date. 18 If a GSI lacks write capacity, writes to the table itself are throttled. 18

Section 4 of 8

Trade-offs

OptionFast readsWrite costUse when
No indexNo Full scan on each query.Lowest.Small tables, or queries that read most rows anyway.
Single-column indexYes , for that column.One more write per row change.One column filters well on its own.
Composite indexYes , if the query matches the leading columns.One write, larger entries.Queries filter on a few columns together: equality first, then range.
Covering (INCLUDE)Yes Can skip the heap.Larger index.Hot queries on tables that change slowly. 2
Partial indexYes , for matching queries only.Low. Only matching rows.Most rows are not interesting, like billed = false.
Global index (GSI)Yes , by any key.Extra write on another partition. Eventually consistent. 18A distributed store needs a second access path.

Simple rule: every index should name the query it serves. If you cannot name one, you probably don't need it.

Section 5 of 8

At work: how a senior uses this

  • Start from the slow query log or pg_stat_statements, not from the schema. Index the queries that run most or cost most.
  • Run EXPLAIN (ANALYZE, BUFFERS) on a copy of production data. Small test data gives different plans.
  • Choose column order by the queries: equality columns first, the range or sort column last.
  • Before dropping an index, list every query that might use it, including ones that use only its trailing columns. GitLab's outage came from one drop. 1
  • On write-heavy tables, count the indexes. Before you call one unused, watch pg_stat_user_indexes on every server for a full business cycle.
  • Build indexes on live tables with CONCURRENTLY, and check afterwards that no invalid index is left behind.
Section 6 of 8

With AI

What to ask the agent

"Here is the table definition, its indexes, and our 10 most frequent queries with their counts. For each query, say which index serves it, or propose one. Explain the column order. List indexes that no query uses."

"Here is the EXPLAIN (ANALYZE, BUFFERS) output for a slow query. Explain each node in plain words. Say where the time goes, and whether a different index or query would help."

"Write a migration that adds this index to a 200-million-row Postgres table without blocking writes. Include a check for an invalid index and a rollback step."

What to check yourself

  • Run every index the agent proposes through EXPLAIN ANALYZE on realistic data. A plan that looks good on 1,000 rows can change at 100 million.
  • Check that the column order fits equality first, then range.
  • Before dropping an index, check pg_stat_user_indexes on every server yourself.
  • Make sure the migration uses CONCURRENTLY and is not wrapped in a transaction.
  • For a partial index, check that the app's queries match its condition exactly, not through a parameter.
Section 7 of 8

Check yourself

1. You have an index on orders (customer_id, created_at). Which query can use it to read only a small, narrow part of the index?

Show answer

WHERE customer_id = 42 AND created_at > '2026-05-01' Equality on the leading column plus a range on the next column gives one narrow range. A condition on created_at alone has no leading column to start from.

2. In MySQL's InnoDB, what does an entry in a secondary index contain besides the indexed columns?

Show answer

The row's primary key, which is then used to find the row in the clustered index. InnoDB stores the primary key columns in every secondary index record and uses them for a second search in the clustered index. A long primary key makes every secondary index bigger.

3. EXPLAIN ANALYZE shows an Index Only Scan with Heap Fetches close to the number of rows returned. What is the most likely reason?

Show answer

Many table pages are not marked all-visible in the visibility map, so Postgres still visits the heap for those rows. An index-only scan only skips the heap for pages whose all-visible bit is set. VACUUM sets those bits.

4. You have a partial index ON orders (created_at) WHERE billed = false. Your app runs a prepared query with WHERE billed = $1 AND created_at > $2. Can Postgres use the partial index?

Show answer

Not reliably. A plan made for any value of $1 cannot use it, because billed = $1 does not prove that billed = false. A partial index is used only when the query's WHERE condition clearly implies the index condition. Postgres docs say parameterized clauses do not work with a partial index. (Early runs of a prepared query may plan with the real value, but you cannot count on it.)

5. pg_stat_user_indexes shows idx_scan = 0 for users_email_key, the index behind a UNIQUE constraint on email. Should you drop it to save write cost?

Show answer

No. It enforces the unique constraint on every insert and update, even if no query reads through it. Postgres creates a unique index for each unique constraint, and that index is how the constraint is enforced. idx_scan counts only scans.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 19 sources and related lessons
  1. GitLab, “Incident Review: INC-6458: Sidekiq queueing SLO violation on urgent-cpu-bound shard” (2026) (opens in a new tab)
    A dropped index on one table slowed queries, filled the connection pool and delayed GitLab.com for 2 hours 36 minutes.
  2. PostgreSQL documentation: Index-Only Scans and Covering Indexes (opens in a new tab)
    Why every Postgres index is a secondary index, why a normal index scan visits the heap, and how INCLUDE and the visibility map help.
  3. MySQL 8.4 Reference Manual: Clustered and Secondary Indexes (opens in a new tab)
    The InnoDB clustered index holds the rows. Secondary index records hold the primary key, which is used for a second lookup.
  4. PostgreSQL documentation: Multicolumn Indexes (opens in a new tab)
    The exact rule for which conditions narrow a multicolumn B-tree scan, skip scan, and advice to use these indexes sparingly.
  5. PostgreSQL 18 release notes (opens in a new tab)
    B-tree skip scans, and EXPLAIN ANALYZE changes (buffers by default, fractional row counts, index searches).
  6. Markus Winand, “Indexing SQL range conditions less than, greater than and between”, Use The Index, Luke! (opens in a new tab)
    A worked example of why equality columns go before range columns.
  7. PostgreSQL documentation: Partial Indexes (opens in a new tab)
    Indexes over a subset of rows, when the planner can use them, and why they are not a substitute for partitioning.
  8. PostgreSQL documentation: Indexes on Expressions (opens in a new tab)
    The lower(col1) example, its cost on writes, and unique indexes on expressions.
  9. PostgreSQL documentation: Unique Indexes (opens in a new tab)
    Unique constraints and primary keys create a unique index for you. How nulls are treated.
  10. PostgreSQL documentation: Using EXPLAIN (opens in a new tab)
    How to read plan nodes and costs, what bitmap scans do, and why EXPLAIN ANALYZE really runs the query.
  11. PostgreSQL documentation: Indexes, Introduction (opens in a new tab)
    Indexes add overhead to every write, and seldom-used indexes should be removed.
  12. PostgreSQL documentation: The Cumulative Statistics System (opens in a new tab)
    The pg_stat_user_indexes view and its idx_scan and last_idx_scan columns.
  13. PostgreSQL documentation: Routine Vacuuming (opens in a new tab)
    VACUUM updates the visibility map, which speeds up index-only scans.
  14. PostgreSQL documentation: CREATE INDEX (opens in a new tab)
    A normal build blocks writes. CONCURRENTLY does not, but it is slower and can leave an invalid index.
  15. PostgreSQL documentation: Index Types (opens in a new tab)
    One paragraph on each index type (B-tree, hash, GiST, SP-GiST, GIN, BRIN) and what it is good for.
  16. PostgreSQL documentation: GIN Indexes (opens in a new tab)
    GIN is an inverted index for arrays, jsonb and text search, and it is slow to update.
  17. PostgreSQL documentation: BRIN Indexes (opens in a new tab)
    A tiny, lossy index for very large tables where values follow the physical row order.
  18. Amazon DynamoDB Developer Guide: Using Global Secondary Indexes in DynamoDB (opens in a new tab)
    Global indexes are updated asynchronously, and a global index without enough write capacity throttles writes to the table.
  19. Amazon DynamoDB Developer Guide: Local secondary indexes (opens in a new tab)
    Local indexes share the table's partition key, allow strongly consistent reads, and limit each partition key value to 10 GB.

Related: B-tree vs LSM-tree · Data models and query languages · Schema migrations without downtime · API pagination and filtering · Sharding and consistent hashing · Search systems and inverted indexes · Geo search and proximity (coming soon)

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper