PostgreSQL查看索引是否失效
在PostgreSQL中,您可以通过查询pg_index
和pg_attribute
视图来检查索引是否失效。以下是一个SQL查询示例,它检查所有索引并确定哪些索引不可用或可能已经失效:
SELECT
n.nspname as "Schema",
t.relname as "Table",
i.relname as "Index",
CASE
WHEN NOT i.indisvalid THEN 'Invalid'
WHEN NOT i.indisready THEN 'Not Ready'
ELSE 'Valid'
END as "Status"
FROM
pg_class t,
pg_namespace n,
pg_index i
WHERE
t.relnamespace = n.oid
AND t.oid = i.indrelid
AND t.relkind = 'r' -- only tables
AND i.indisprimary = false -- exclude primary keys
AND i.indisvalid = false -- only invalid indexes
UNION ALL
SELECT
n.nspname as "Schema",
t.relname as "Table",
NULL as "Index",
'No Index' as "Status"
FROM
pg_class t,
pg_namespace n
WHERE
t.relnamespace = n.oid
AND t.relkind = 'r' -- only tables
AND NOT EXISTS (
SELECT 1
FROM pg_index i
WHERE i.indrelid = t.oid AND i.indisprimary = false
) -- no other indexes
ORDER BY
"Schema",
"Table",
"Index" IS NOT NULL DESC;
这个查询将列出所有无效的索引以及没有索引的表。如果您想要检查特定的索引,可以在WHERE
子句中添加更多的条件来指定表名和索引名。
评论已关闭