---
title: "Why is the first query on a rarely used index slow, and the repeat fast? | Proofline"
description: "A B-tree index keeps the entries of dead rows until vacuum, and an ordinary index scan marks them in passing so later scans skip them."
url: https://proofline.sh/learn/postgres-dead-index-entries-partial-index/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Why is the first query on a rarely used index slow, and the repeat fast?

A B-tree index keeps the entries of dead rows until vacuum, and an ordinary index scan marks them in passing so later scans skip them. An index that one dashboard reads a few times a day gets no such marking, so its first scan after the queue has churned visits the table for every dead entry, and the repeat is fast. Check whether a frequently scanned index can serve the query. If the newest entry alone determines the answer, use a query that can stop there.

Capacity overruns The Proofline team December 2, 2026 7 min read

## The symptom

A job queue table has a status column and a partial index for each kind of reader. Workers claim jobs through one index all day. An operations page asks for overdue jobs through another, a few times an hour at most. The page's first load takes over a second, a reload takes a fraction of a millisecond, and the query returns zero rows both times.

The plan does not change between the two calls. `EXPLAIN (ANALYZE, BUFFERS)` shows the same index scan with thousands of buffers the first time and a few dozen the second. Autovacuum resets the pattern: right after it runs, the first call is fast too.

## What the index keeps after an update

A PostgreSQL index entry points at one row version. When an update changes a column that an index covers, or a column in a partial index's `WHERE` clause, PostgreSQL writes a new row version and new index entries. The old entries stay in the index until vacuum removes them, even when the new row version no longer qualifies for that partial index. A job that moves from `PENDING` to `DONE` leaves a dead entry behind in every partial index that held it.

A scan that meets a dead entry has to visit the table to learn the row is gone. A plain index scan then sets the entry's `LP_DEAD` bit, so the next scan of that page skips it without a table visit. The [B-tree implementation notes](https://www.postgresql.org/docs/current/btree.html#BTREE-DELETION) describe this marking as opportunistic: entries are cleaned only when "recent index scans set the LP\_DEAD bits of affected items in passing". The same notes say bottom-up deletion, the other cleanup path, targets updates that do not logically change the index's columns. A status change does change them, so only scans and vacuum remove these entries.

Two consequences follow. The marks belong to one index, so a busy worker index can be clean while a quiet index on the same rows is full of unmarked entries. And a bitmap index scan does not set the marks at all, so a query planned as a bitmap scan pays the table visits on every call until vacuum.

## The lab

The lab needs Docker and takes under a minute. Autovacuum is off on the table so that the dead entries stay put.

```
docker run -d --rm --name pl-b-dead-index -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-b-dead-index psql -U postgres
```

```
CREATE TABLE jobs (
  id bigserial PRIMARY KEY,
  kind text NOT NULL,
  status text NOT NULL,
  due_at timestamptz NOT NULL,
  payload text NOT NULL
) WITH (autovacuum_enabled = off);
-- The workers' index: every claim scans it.
CREATE INDEX jobs_unfinished_idx ON jobs (kind, due_at)
  WHERE status IN ('PENDING', 'RUNNING');
-- The dashboard's index: one page reads it.
CREATE INDEX jobs_due_idx ON jobs (due_at) WHERE status = 'PENDING';

-- 100,000 jobs arrive and finish.
INSERT INTO jobs (kind, status, due_at, payload)
SELECT 'sync', 'PENDING', now() - interval '1 hour' + g * interval '30 ms', repeat('x', 200)
FROM generate_series(1, 100000) g;
UPDATE jobs SET status = 'DONE';
ANALYZE jobs;
```

Run the worker's claim query three times, then the dashboard's overdue query twice, each under `EXPLAIN (ANALYZE, BUFFERS)`:

```
SELECT id FROM jobs
WHERE kind = 'sync' AND status IN ('PENDING', 'RUNNING') AND due_at < now()
ORDER BY due_at LIMIT 10;

SELECT id FROM jobs
WHERE status = 'PENDING' AND due_at < now()
ORDER BY due_at LIMIT 100;
```

On PostgreSQL 18.7 every call returned zero rows. The buffer counts were:

```
Index Scan using jobs_unfinished_idx   1st  37.1 ms  shared hit=4104
Index Scan using jobs_unfinished_idx   2nd   0.9 ms  shared hit=386
Index Scan using jobs_unfinished_idx   3rd   0.6 ms  shared hit=386
Index Scan using jobs_due_idx          1st  11.9 ms  shared hit=3883
Index Scan using jobs_due_idx          2nd   0.6 ms  shared hit=275
```

The workers' first scan cleaned only their own index. The dashboard's first scan still visited the table for each of its 100,000 dead entries, and only its repeat was cheap. After `VACUUM jobs`, the dashboard query read one buffer.

Two further runs show the fixes and the trap. After another 100,000 jobs churned and the worker query ran twice, `DROP INDEX jobs_due_idx` moved the dashboard query onto the workers' index. Its first call then read 391 buffers, with a sort over zero rows, because the workers had already marked those entries. A bitmap scan of the workers' index, forced with `enable_indexscan = off`, read 3,720 buffers on the first call and 3,720 on the second: it never marks anything.

All of the lab's buffers were cache hits. In production the cold pages also come from disk, which is where the seconds go.

## Read it on a real table

Look for three signs on the slow query:

-   `EXPLAIN (ANALYZE, BUFFERS)` shows the same plan with far more buffers on the first call than on an immediate repeat, and few rows either way.
-   `pg_stat_user_indexes.idx_scan` for that index rises only when this query runs. Read it before and after a few calls.
-   `pg_stat_user_tables.n_dead_tup` is high and `last_autovacuum` is some time ago. Right after a vacuum, the first call is fast.

## Choose a fix

**Route the query to a busy index.** If another index already covers the rows and your workers scan it all day, drop the quiet index or rewrite the predicate so the planner cannot use it. The query may cost a little more when warm, but it stops having a cold first call. Check that every query that used the dropped index still matches another index's predicate, so none falls back to a sequential scan. The [unused index guide](/learn/unused-index-finding/) covers what to check before a drop.

**Read only the newest entry.** If the newest job's status determines the whole chain's status, read that member through an index ordered by time using `ORDER BY ... DESC LIMIT 1`. When older members can remain unfinished independently, retain the original membership check. A backward scan stops at the first entry, so dead versions of older members below it are never visited.

**Vacuum more often.** A lower per-table threshold shortens the time the dead range can grow, but it does not remove the cold call; it only makes it smaller. The [autovacuum documentation](https://www.postgresql.org/docs/current/routine-vacuuming.html#AUTOVACUUM) gives the formula. Dead rows left by a large backfill are a related case, covered in [dead tuples after a backfill](/learn/postgres-backfill-dead-tuples-vacuum/).

## Where this advice stops

-   A dead entry can be marked only when its row version is dead to every open transaction. A long transaction or a replication slot that holds the cleanup horizon back keeps all scans paying, on every index.
-   If the query returns many live rows, the table visits are real work, and none of this applies.

## Where this came from

Proofline found this in its own job queue table and shipped the fixes in its production releases of 28 and 30 November 2026. An overdue query on an operations page read a partial index that nothing else scanned: its first call took 1,625 ms with 4,982 buffer hits and 2,346 reads, and the repeat took 0.086 ms. Shortening the vacuum interval from a median of about 12 hours to 3.5 hours left the cold call in place, and dropping the index moved the query to the workers' index. A post-release probe measured 8.32 ms with no disk reads on the first scan. Its row count differed from the earlier sample. A second probe, which checked a chain of minute-by-minute polls, averaged 460 ms over 1,723 calls with a maximum of 17 seconds, 763 of its 792 seconds in reads; checking the newest poll first let the common path skip the full probe. The slower probe remained for cases the latest poll could not settle. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. [Start a free GitHub review](https://proofline.sh/orgs/plan?offer=free150) · [Eligibility and fair-use terms](/free-code-review/)

## Questions

### Why is an index scan fast the second time with the same plan?

The first plain index scan visits the table for each dead entry and marks it with the `LP_DEAD` bit. The second scan skips marked entries without touching the table. Caching helps too, but the buffer count drops even when every page was already in memory.

### Does a bitmap index scan clean up dead index entries?

No. A bitmap scan collects entries first and visits the table later, so it cannot mark the entries it found dead. It pays the same table visits on every call until vacuum removes them.

### Is it worth keeping a partial index that only one query uses?

Only if that query runs often enough to keep the index marked, or if vacuum runs soon after each burst of churn. Otherwise its first call after a quiet period pays for every row that left the index's predicate.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Vacuum between backfill batches to keep the table from doubling](/learn/postgres-backfill-dead-tuples-vacuum/)
    
    Capacity overruns The Proofline team November 22, 2026 3 min read
    
-   ### [Should you drop an index that shows idx\_scan = 0?](/learn/unused-index-finding/)
    
    Code review The Proofline team November 25, 2026 5 min read
