The list of all the queries

Multiple simple keys with integer values

Query goal: Find base tables that have more than one primary key or unique constraints that involve exactly one integer column. Do not overcomplicate the database. Perhaps some column in the table is redundant.
Notes about the query: In case of the string_agg function, the line break (br) tag is used as a part of the separator for the better readability in case the query result is displayed in a web browser.
Query type: Problem detection (Each row in the result could represent a flaw in the design)
Query reliability: Low (Many false-positive results)
Query license: MIT License
Data source: INFORMATION_SCHEMA+system catalog
SQL query: Click on query to copy it

with simple_keys as (select 
n.nspname as table_schema,
c.relname as table_name, 
(SELECT a.attname FROM pg_attribute a WHERE a.attrelid = c.oid AND a.attnum = o.conkey[1] AND a.attisdropped = FALSE)  AS column_name
from pg_constraint o inner join pg_class c on c.oid = o.conrelid
inner join pg_namespace n on c.relnamespace=n.oid
where o.contype in ('u', 'p')
and c.relkind = 'r' 
and cardinality(o.conkey)=1
and n.nspname NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL)),
integer_columns AS (SELECT table_schema, table_name, column_name
FROM INFORMATION_SCHEMA.columns
WHERE data_type IN ('smallint', 'integer', 'bigint')
AND (table_schema, table_name) IN (SELECT table_schema, table_name
FROM INFORMATION_SCHEMA.tables 
WHERE table_type IN ('BASE TABLE')) 
AND table_schema NOT IN (SELECT schema_name
FROM INFORMATION_SCHEMA.schemata
WHERE schema_name<>'public' AND
schema_owner='postgres' AND schema_name IS NOT NULL))
SELECT table_schema, table_name, Count(*) AS number_of_simple_int_keys, string_agg (column_name, ';<br>' ORDER BY column_name) AS simple_int_keys
FROM simple_keys
WHERE (table_schema, table_name, column_name) IN (SELECT table_schema, table_name, column_name
FROM integer_columns)
GROUP BY table_schema, table_name
HAVING Count(*) >1
ORDER BY Count(*) DESC, table_schema, table_name;

Categories where the query belongs to

Category nameCategory description
UniquenessQueries of this category provide information about uniqueness constraints (PRIMARY KEY, UNIQUE, EXCLUDE) as well as unique indexes.
Validity and completenessQueries of this category provide information about whether database design represents the world (domain) correctly (validity) and whether database design captures all the information about the world (domain) that is correct and relevant (completeness).

The list of all the queries