Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active February 19, 2022 23:07
Show Gist options
  • Save vielhuber/bda4983431cd0ac7080b to your computer and use it in GitHub Desktop.
Save vielhuber/bda4983431cd0ac7080b to your computer and use it in GitHub Desktop.
PostgreSQL: Check if a constraint / foreign key exists #sql
-- example
SELECT COUNT(*) FROM information_schema.constraint_column_usage where constraint_name = 'table_name_foreign_table_id_foreign';
-- general
WITH
table_name AS (VALUES ('addresses')),
foreign_table_id AS (VALUES ('club_id'))
SELECT COUNT(*) > 0 FROM information_schema.constraint_column_usage where constraint_name = (TABLE table_name)||'_'||(TABLE foreign_table_id)||'_foreign';
-- get all foreign keys for specific table
WITH
table_name AS (VALUES ('addresses')),
table_schema AS (VALUES ('public'))
SELECT tc.constraint_name,
kcu.column_name AS childcolumn,
ccu.table_name AS parenttable,
ccu.column_name AS parentcolumn
FROM information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
INNER JOIN information_schema.constraint_column_usage ccu
ON tc.constraint_name = ccu.constraint_name
WHERE tc.table_schema = (TABLE table_schema)
AND tc.table_name = (TABLE table_name)
AND tc.constraint_type = 'FOREIGN KEY'
AND kcu.table_schema = (TABLE table_schema)
AND ccu.table_schema = (TABLE table_schema);
@awaism551
Copy link

where prm_schema is the schema for which you want to target, and prm_table is the table in prm_schema, for which you want to get list of foreign keys

@awaism551
Copy link

SELECT COUNT(*) FROM information_schema.constraint_column_usage where constraint_name = 'table_name_foreign_table_id_foreign'; this query won't work if constraint name is in some other format

@vielhuber
Copy link
Author

Thanks for your feedback, very helpful. I've enhanced the gist based on your input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment