List foreign keys and the tables/columns they point at
To understand a schema or plan a data load, you need every foreign key and where it points. This recipe lists each FK with its source column and the referenced target.
The task
A delete fails with a foreign-key violation and nothing in the application code says which relationship caused it. You need both ends of every FK relationship named.
The snippet
Written for PostgreSQL. Versions for MySQL and SQLite are under Variations.
SELECT con.conname AS constraint_name,
src.relname AS table_name,
src_col.attname AS column_name,
tgt.relname AS referenced_table,
tgt_col.attname AS referenced_column
FROM pg_constraint con
JOIN pg_class src ON src.oid = con.conrelid
JOIN pg_class tgt ON tgt.oid = con.confrelid
JOIN unnest(con.conkey) WITH ORDINALITY AS sk(attnum, ord) ON true
JOIN unnest(con.confkey) WITH ORDINALITY AS tk(attnum, ord) ON tk.ord = sk.ord
JOIN pg_attribute src_col
ON src_col.attrelid = src.oid AND src_col.attnum = sk.attnum
JOIN pg_attribute tgt_col
ON tgt_col.attrelid = tgt.oid AND tgt_col.attnum = tk.attnum
WHERE con.contype = 'f'
ORDER BY src.relname, con.conname, sk.ord;
작동 방식
pg_constraint stores a foreign key as two matching arrays of column numbers: conkey on the referencing side and confkey on the referenced side. Unnesting both with ordinality pairs them up positionally, which handles composite foreign keys correctly. contype 'f' selects foreign keys only; 'p', 'u', 'c' and 'x' are primary key, unique, check and exclusion constraints. Add a filter on src.relnamespace to limit the list to one schema.
Variations
MySQL
MySQLSELECT kcu.constraint_name, kcu.table_name, kcu.column_name,
kcu.referenced_table_name, kcu.referenced_column_name,
rc.delete_rule, rc.update_rule
FROM information_schema.key_column_usage kcu
JOIN information_schema.referential_constraints rc
ON rc.constraint_schema = kcu.constraint_schema
AND rc.constraint_name = kcu.constraint_name
WHERE kcu.table_schema = 'mydb'
AND kcu.referenced_table_name IS NOT NULL
ORDER BY kcu.table_name;
SQLite
SQLitePRAGMA foreign_key_list(orders);
-- one row per FK column: id, seq, table, from, to,
-- on_update, on_delete, match
Questions that come up
How do I plan table load order from this output?
Load referenced tables first: any table that appears in referenced_table must be populated before the table in table_name. The table-dependency-order recipe turns this into an ordered list.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.