Learning center

Why is "the latest row where X" slow in PostgreSQL, and how does a partial index fix it?

A query for the newest row that matches a filter walks an index backwards and discards every newer row that fails the filter. Its cost grows with the rows written since the last match, not with the result. A partial index that holds only matching rows makes the answer the first entry it reads.

The symptom#

A ledger table has an index on (org_id, created_at). A billing page asks when an organization last received credit:

SELECT created_at FROM ledger
WHERE org_id = $1 AND amount > 0
ORDER BY created_at DESC
LIMIT 1;

For most organizations it returns in a millisecond. For one it takes seconds, then tens of seconds under load, and it gets slower every day. The organizations it is slow for are the ones that have spent heavily since their last top-up, which are the ones most likely to be looking at the billing page.

Why the backward scan reads so much#

The planner sees ORDER BY created_at DESC LIMIT 1 and an index whose entries for one organization are already sorted by created_at. The documentation on indexes and ORDER BY describes the trade it makes: an index scan in the requested order can stop as soon as it has LIMIT rows, which is far cheaper than sorting, as long as the first rows it reads qualify.

Here they do not. amount is not in the index, so for each entry the scan visits the table row, checks amount > 0, and moves to the next older entry when it fails. An organization with 1.5 million debits since its last credit costs 1.5 million table row visits to return one timestamp. The planner cannot see this coming. It estimates how many rows match the filter overall, not where in the order they sit.

The lab#

The lab needs Docker and loads in under 30 seconds. Organization 1 has one top-up followed by 1.5 million debits; 500 other organizations receive rows, with a credit on every tenth generated row.

docker run -d --rm --name pl-a-partial-latest -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-a-partial-latest psql -U postgres
CREATE TABLE ledger (
  id bigserial PRIMARY KEY,
  org_id int NOT NULL,
  created_at timestamptz NOT NULL,
  amount bigint NOT NULL,
  kind text NOT NULL
);
CREATE INDEX ledger_org_created_idx ON ledger (org_id, created_at);

INSERT INTO ledger (org_id, created_at, amount, kind)
VALUES (1, '2026-10-01', 50000000, 'TOPUP');
INSERT INTO ledger (org_id, created_at, amount, kind)
SELECT 1, timestamptz '2026-10-02' + g * interval '1 second', -10, 'DEBIT'
FROM generate_series(1, 1500000) g;
INSERT INTO ledger (org_id, created_at, amount, kind)
SELECT 2 + g % 500, timestamptz '2026-10-01' + g * interval '1 second',
       CASE WHEN g % 10 = 0 THEN 1000 ELSE -5 END,
       CASE WHEN g % 10 = 0 THEN 'GRANT' ELSE 'DEBIT' END
FROM generate_series(1, 500000) g;
VACUUM ANALYZE ledger;

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT created_at FROM ledger
WHERE org_id = 1 AND amount > 0
ORDER BY created_at DESC LIMIT 1;

On PostgreSQL 18.7:

Limit (actual time=2984.778..2984.779 rows=1.00 loops=1)
  ->  Index Scan Backward using ledger_org_created_idx on ledger
        Index Cond: (org_id = 1)
        Filter: (amount > 0)
        Rows Removed by Filter: 1500000
        Buffers: shared read=18251
Execution Time: 2984.809 ms

Across three runs the time ranged from 392 ms to 2,985 ms, depending on what was cached. The buffer count stayed at about 18,250.

Rows Removed by Filter is the number of debits since the top-up, and the buffers are mostly table pages visited to read amount. Now add an index that holds only credits:

CREATE INDEX CONCURRENTLY ledger_credit_created_idx
  ON ledger (org_id, created_at) WHERE amount > 0;

The same query becomes:

Limit (actual time=0.042..0.043 rows=1.00 loops=1)
  ->  Index Only Scan Backward using ledger_credit_created_idx on ledger
        Index Cond: (org_id = 1)
        Heap Fetches: 0
        Buffers: shared hit=3
Execution Time: 0.070 ms

The scan reads three pages and stops at the organization's newest credit. The new index is 1,552 kB against 66 MB for the full one, because it holds 50,001 of the 2 million rows. It also costs nothing on a debit insert, since PostgreSQL skips partial index maintenance for rows that do not satisfy the predicate.

Make the predicate match the query#

The planner uses a partial index only when it can prove, at planning time, that the query's WHERE clause implies the index predicate. Two consequences catch people.

First, the condition must be visible to the planner. A literal amount > 0 matches. A parameter does not, under a generic plan, because the planner cannot prove that amount > $2 implies amount > 0 for every value of $2. In the lab, a prepared amount > $2 under force_generic_plan goes back to the full index:

Limit
  ->  Index Scan Backward using ledger_org_created_idx on ledger
        Index Cond: (org_id = $1)
        Filter: (amount > $2)

Executed with $2 = 0, that plan takes 464 ms and again removes 1,500,000 rows. Write the constant into the SQL text. If your query builder parameterizes everything, check the plan of the statement the application actually prepares, as in checking an index against the query the app sends.

Second, reusing an existing partial index by adding its predicate to your query changes the query. The production case below had a funding index whose predicate excluded debits and one kind of free grant. Adding that predicate would have let the planner use the funding index and omitted any grant that was the newest positive entry. A new index with exactly the query's predicate kept every result the same.

The production case#

A billing balance read looked up an out-of-credits organization's last credit with the query above, against a ledger indexed on (organization_id, created_at). For Proofline's own organization, the plan was an Index Scan Backward with Rows Removed by Filter: 146062 over 104,030 buffers. It took 6,543 ms on a cold cache when run by hand, and the application logged 25 to 28 seconds for it under load.

The fix was one online migration that built a partial index on (organization_id, created_at) WHERE amount > 0, with the query text unchanged. A rehearsal on a synthetic ledger with one organization's top-up followed by 1.5 million debits planned it as an index-only backward scan: 4 buffers, 0.05 ms, returning the top-up's time.

Where this advice stops#

  • If most rows match the filter, the backward scan already stops early and the partial index buys little.
  • A filter on a value the query passes in, such as a kind chosen by the user, cannot have one partial index per value. Put the column in the index instead, (org_id, kind, created_at), so the condition becomes an index condition rather than a filter.
  • Adding amount to the full index as a trailing or INCLUDE column removes the table visits, but the scan still steps over every debit entry. The cost still grows with the debits, only more slowly.
  • The predicate is fixed at creation. If the meaning of "credit" changes, the index needs to be rebuilt with the new predicate, and the query with it.

Where this came from#

Proofline found this in its own credit ledger and included the partial index in a production release tagged 1 December 2026. The plan figures in The production case are that ledger's readings before the change. Proofline reviews GitHub pull requests, including migrations like this one; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

Why does ORDER BY ... DESC LIMIT 1 scan so many rows?

The index provides the order, but the filter column is not in it. The scan checks each row from newest to oldest and stops at the first that passes, so it reads every newer row that fails.

Will PostgreSQL use a partial index with a parameterized predicate?

Only when the planner can prove the query's condition implies the index predicate. A literal in the SQL text can be proven; a bound parameter under a generic plan cannot.

Does a partial index slow down inserts?

Only inserts whose rows satisfy the predicate update it. Rows outside the predicate skip it, so in a ledger with mostly debits the credit index costs almost nothing to maintain.

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.

Start free with GitHub

Related reading