Hard postgresql sql

How do you find and safely drop unused PostgreSQL indexes in a live service?

The 30 second answer

Extra indexes slow every INSERT, UPDATE and DELETE. I compare pg_stat_user_indexes with the queries the service actually runs, check replicas and other owners, and I drop leftover indexes with DROP INDEX CONCURRENTLY rather than a blocking DROP INDEX.

Could you say this in an interview?

Every secondary index is maintained on write. On a table that takes a high insert rate, leftover indexes add CPU, WAL and storage without helping a query the service still runs. Before I drop anything, I write down the access paths the application actually uses, then I compare that list with pg_stat_user_indexes. A long-lived idx_scan of 0 is a candidate, but it is not proof: statistics can have been reset, a replica may be the one serving the query, and a monthly report on another service may be the only consumer.

I do not drop unique, primary-key or constraint indexes just because they look quiet, and I confirm the statement against a recent EXPLAIN (ANALYZE, BUFFERS) of the remaining queries. When I do drop an unused index on a live system, I use DROP INDEX CONCURRENTLY so the table is not locked for ordinary writes for the whole drop. I ship that change through the same migration process I use for schema changes, and I watch write latency and query plans after it lands.

class PaymentAccessDemo {
    public static void main(String[] args) {
        String[] liveQueries = {
            "findByTransactionReference",
            "findByMerchantIdOrderByCreatedAtDesc",
            "updateStatus"
        };
        for (String query : liveQueries) {
            System.out.println(query);
        }
    }
}

Output, compiled with javac --release 17:

findByTransactionReference
findByMerchantIdOrderByCreatedAtDesc
updateStatus

Those are the lookups I would check first in pg_stat_user_indexes and in EXPLAIN. An index that does not support one of them, and that no other owner can justify, is the one I consider removing.

SELECT schemaname, relname, indexrelname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
WHERE relname = 'payments'
ORDER BY idx_scan, indexrelname;

DROP INDEX CONCURRENTLY IF EXISTS idx_payments_unused;
Sources (3)
  1. PostgreSQL docs: Indexespostgresql.org
  2. PostgreSQL docs: Viewing Statistics, pg_stat_all_indexespostgresql.org
  3. PostgreSQL docs: DROP INDEXpostgresql.org