Goal Find all tables that rows have been physically sorted based on an index.
Type General (Overview of some aspect of the database.)
License MIT License
Data Source system catalog only
SQL Query
WITH ind AS (SELECT 
(select nspname from pg_namespace where oid=c.relnamespace) AS table_schema,
i.relname AS table_name,
i.oid AS ind_table_oid,
ix.indkey AS index_col,
c.relname AS index_name,
ix.indisprimary,
ix.indisunique,
pg_get_indexdef(ix.indexrelid) as index_def
FROM pg_index ix INNER JOIN pg_class c ON ix.indexrelid=c.oid
INNER JOIN pg_class i ON ix.indrelid=i.oid
WHERE ix.indisclustered=true),
ind_unnest AS (SELECT table_schema, table_name, index_name, indisprimary, indisunique, index_def, ind_table_oid, ind_col_num, ordin
FROM ind, Unnest(ind.index_col) WITH ORDINALITY AS k(ind_col_num, ordin)),
ind_with_names as (SELECT table_schema, table_name, index_name, indisprimary, indisunique,  array_agg(a_index.attname ORDER BY ordin) AS index_col, index_def
FROM ind_unnest i INNER JOIN pg_attribute a_index on i.ind_col_num = a_index.attnum AND i.ind_table_oid = a_index.attrelid AND a_index.attisdropped = false
GROUP BY table_schema, table_name, index_name, indisprimary, indisunique, index_def)
SELECT table_schema, table_name, index_col,  index_name, indisprimary, indisunique,  index_def
FROM ind_with_names
ORDER BY table_schema, table_name, index_col;

Collections

This query belongs to the following collections:

NameDescription
Find problems by overviewQueries that results point to different aspects of database that might have problems. A human reviewer has to decide based on the results as to whether there are problems or not .
Categories

This query is classified under the following categories:

NameDescription
PerformanceQueries of this category provide information about indexes in a database.

Further reading and related materials:

Reference
https://www.postgresql.org/docs/current/sql-cluster.html