Is there a way using SQL to list all foreign keys for a given table? I know the table name / schema and I can plug that in.
+3
A:
You can use the PostgreSQL system catalogs. Maybe you can query pg_constraint to ask for foreign keys. You can also use the Information Schema
Guido
2009-07-20 08:18:57
+3
A:
You can do this via the information_schema tables. For example:
SELECT
tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND table_name='mytable';
ollyc
2009-07-20 08:28:57
+1
A:
psql does this, and if you start psql with:
psql -E
it will show you exactly what query is executed. In the case of finding foreign keys, it's:
SELECT conname,
pg_catalog.pg_get_constraintdef(r.oid, true) as condef
FROM pg_catalog.pg_constraint r
WHERE r.conrelid = '16485' AND r.contype = 'f' ORDER BY 1
In this case, 16485 is the oid of the table I'm looking at - you can get that one by just casting your tablename to regclass like:
WHERE r.conrelid = 'mytable'::regclass
Magnus Hagander
2009-07-20 14:56:41
A:
I created little tool to query and then compare database schema: Dump PostgreSQL db schema to text
There is info about FK, but ollyc response gives more details.
Michał Niklas
2009-07-21 05:27:53