Partial and Covering Indexes in Postgres

Partial and Covering Indexes in Postgres

So we wanted a queue like it looks after one year of work, ten million jobs and almost all of them done, only 300 still waiting, we generated this in Postgres 18 on our laptop, it took a while to insert, and put two indexes on priority and created_at, one usual and one which has WHERE finished_at IS NULL on the end.

CREATE INDEX CONCURRENTLY jobs_waiting
  ON jobs (priority, created_at)
  WHERE finished_at IS NULL;
add_index :jobs, [:priority, :created_at],
  where: "finished_at IS NULL",
  name: "jobs_waiting",
  algorithm: :concurrently

Sizes, and here we laughed. The normal index 67 MB, the partial 16 kB, the table itself 651 MB. For the worker which asks every second give us the next ten, the small one answered in 0.028 ms reading two pages, so what for do we carry the 67 MB, we dropped it.

Then we tried to break it. The condition we changed to IS NOT DISTINCT FROM NULL and it still took the small index, hm, so we thought the docs are scaring us. But when the NULL comes as a parameter in a prepared statement, with generic plan forced, then it is a parallel seq scan over the whole table, 283 ms, because Postgres at planning time does not know what is inside the $1 and can't promise that the index has those rows. So write IS NULL in the query by your hand.

The second thing is covering index, our orders table had two million rows and with INCLUDE of status and total the plan was telling Index Only Scan, but also Heap Fetches 10 on limit 10, so what kind of only is this.

CREATE INDEX CONCURRENTLY orders_user_recent
  ON orders (user_id, created_at DESC)
  INCLUDE (status, total_cents);

SELECT created_at, status, total_cents
FROM orders
WHERE user_id = 42
ORDER BY created_at DESC
LIMIT 10;

The reason is we didn't vacuum after loading. After VACUUM the same query shows Heap Fetches 0 and only 4 buffers instead of 13. And then we updated status for this user, 2000 rows, and again Heap Fetches 20 and 43 buffers, so on a table where rows are changing all the time the index only scan is only on paper if autovacuum is not coming often enough, that is why under the post there is the setting for it.

ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02);

See also: indexing basics and reading query plans.