-
Notifications
You must be signed in to change notification settings - Fork 9
/
unused_indexes.sql
34 lines (32 loc) · 1.25 KB
/
unused_indexes.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
* Copyright (c) 2019-2024. Ivan Vakhrushev and others.
* https://github.com/mfvanek/pg-index-health-sql
*
* Licensed under the Apache License 2.0
*/
-- Finds potentially unused indexes.
-- This sql query have to be executed on all hosts in the cluster.
-- The final result can be obtained as an intersection of results from all hosts.
with
foreign_key_indexes as (
select i.indexrelid
from
pg_catalog.pg_constraint c
inner join lateral unnest(c.conkey) with ordinality u(attnum, attposition) on true
inner join pg_catalog.pg_index i on i.indrelid = c.conrelid and (c.conkey::int[] <@ i.indkey::int[])
where c.contype = 'f'
)
select
psui.relid::regclass::text as table_name,
psui.indexrelid::regclass::text as index_name,
psui.idx_scan as index_scans,
pg_relation_size(i.indexrelid) as index_size
from
pg_catalog.pg_stat_user_indexes psui
inner join pg_catalog.pg_index i on i.indexrelid = psui.indexrelid
where
psui.schemaname = :schema_name_param::text and
not i.indisunique and
i.indexrelid not in (select * from foreign_key_indexes) and /* retain indexes on foreign keys */
psui.idx_scan < 50::integer
order by psui.relname, pg_relation_size(i.indexrelid) desc;