Is there a query that will do that?
I found some queries that can do this for one table, but I wasn't able to modify it so I can see:
tablename | column | type
Is there a query that will do that?
I found some queries that can do this for one table, but I wasn't able to modify it so I can see:
tablename | column | type
This is more accurate answer:
select tc.table_schema, tc.table_name, kc.column_name
from
information_schema.table_constraints tc,
information_schema.key_column_usage kc
where
tc.constraint_type = 'PRIMARY KEY'
and kc.table_name = tc.table_name and kc.table_schema = tc.table_schema
and kc.constraint_name = tc.constraint_name
order by 1, 2;
You missed the and kc.constraint_name = tc.constraint_name part, so it lists all constraints.
Something like this:
select tc.table_schema, tc.table_name, kc.column_name
from information_schema.table_constraints tc
join information_schema.key_column_usage kc
on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name
where tc.constraint_type = 'PRIMARY KEY'
and kc.ordinal_position is not null
order by tc.table_schema,
tc.table_name,
kc.position_in_unique_constraint;
Please consider this also. This will generate the script to alter all the tables.
SELECT STRING_AGG(FORMAT('ALTER TABLE %s CLUSTER ON %s;', A.table_name, A.constraint_name), E'\n') AS SCRIPT
FROM
(
SELECT FORMAT('%s.%s', table_schema, table_name) AS table_name, constraint_name
FROM information_schema.table_constraints
WHERE UPPER(constraint_type) = 'PRIMARY KEY'
ORDER BY table_name
) AS A;
I think to get primary key and foreign key should do like this. kc.position_in_unique_constraint is not null this condition may only get foreign keys.
select tc.table_schema, tc.table_name, kc.column_name,tc.constraint_type
from
information_schema.table_constraints tc
JOIN information_schema.key_column_usage kc
on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema
and kc.constraint_name = tc.constraint_name
where
--kc.position_in_unique_constraint is not null
order by tc.table_schema,
tc.table_name,
kc.position_in_unique_constraint;