Query goal: | Find pairs of non-function based unique indexes that cover the same set of columns. Include indexes that support a constraint (primary key, unique, exclude), i.e., these indexes have been automatically created due to the constraint declaration. For instance, it helps us to find unique indexes that have been defined to already unique columns. |
Notes about the query: | The query does not take into account the order of colums in the index, i.e., indexes (a, b) and (b, a) are considered duplicates. |
Query type: | Problem detection (Each row in the result could represent a flaw in the design) |
Query reliability: | High (Few or no false-positive results) |
Query license: | MIT License |
Fixing suggestion: | Drop the duplicates. Do not drop the duplicate that supports a constraint but a duplicate that is user-defined. |
Data source: | system catalog only |
SQL query: | Click on query to copy it
WITH indexes AS (SELECT n.nspname AS sch, c2.relname AS tbl, c.relname AS indx, string_agg(a.attname, ',' ORDER BY a.attname) AS clm, EXISTS (SELECT * FROM pg_catalog.pg_constraint AS o WHERE o.conindid=i.indexrelid) AS is_constraint FROM pg_catalog.pg_class AS c INNER JOIN pg_catalog.pg_index AS i ON i.indexrelid = c.oid INNER JOIN pg_catalog.pg_class AS c2 ON i.indrelid = c2.oid INNER JOIN pg_catalog.pg_namespace AS n ON c.relnamespace = n.oid INNER JOIN pg_catalog.pg_authid AS u ON n.nspowner = u.oid INNER JOIN pg_catalog.pg_attribute AS a ON a.attrelid = c.oid WHERE c.relkind = 'i' AND i.indexprs IS NULL AND i.indisunique=TRUE AND a.attnum>=1 AND a.attisdropped = FALSE AND (n.nspname = 'public' OR u.rolname <> 'postgres') GROUP BY n.nspname, c2.relname, c.relname, i.indisunique, is_constraint) SELECT A.sch AS table_schema, A.tbl AS table_name, A.is_constraint AS is_idx1_constraint, A.indx AS idx1, A.clm AS idx1_columns, B.clm AS idx2_columns, B.is_constraint AS is_idx2_constraint, B.indx AS idx2 FROM indexes AS A, indexes AS B WHERE A.sch=B.sch AND A.tbl=B.tbl AND A.indx>B.indx AND a.clm=b.clm ORDER BY A.sch, A.tbl, A.indx, B.indx; |
Collection name | Collection description |
---|---|
Find problems about integrity constraints | A selection of queries that return information about the state of integrity constraints in the datadabase. Contains all the types of queries - problem detection, software measure, and general overview |
Find problems automatically | Queries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not . |
Category name | Category description |
---|---|
Performance | Queries of this category provide information about indexes in a database. |
Uniqueness | Queries of this category provide information about uniqueness constraints (PRIMARY KEY, UNIQUE, EXCLUDE) as well as unique indexes. |