Skip to content

Instantly share code, notes, and snippets.

@mfollett
Created September 25, 2014 21:54
Show Gist options
  • Save mfollett/fc1722841ed572d35f75 to your computer and use it in GitHub Desktop.
Save mfollett/fc1722841ed572d35f75 to your computer and use it in GitHub Desktop.
Query to generate query to check foreign key constraints
-- Generates a SQL query that validates that none of your foreign key
-- constrainted columns are invalid (values that don't exist in the column that
-- defines valid values).
-- The query returns a list of foreign key constraints and the number of
-- violations present. If you want this query to return all constraints then
-- you can lop off the 'foo WHERE count > 0' below, this'll cause it to return
-- all foreign key constraints and the number of violations, even when 0.
SELECT 'SELECT * FROM (' || string_agg(query, ' UNION ') || ') foo WHERE count
> 0;' FROM (
SELECT 'SELECT count(*), ' || ''''|| constraint_name || '''' || ' FROM ' || table_name || ' WHERE ' || column_name || ' NOT IN ( SELECT ' || foreign_column_name || ' FROM ' || foreign_table_name || ')' query
FROM (
-- This portion of the query was adapted from:
-- https://stackoverflow.com/questions/1152260/postgres-sql-to-list-table-foreign-keys
SELECT
table_constraint.constraint_name,
table_constraint.table_name,
key_column_usage.column_name,
constraint_column_usage.table_name AS foreign_table_name,
constraint_column_usage.column_name AS foreign_column_name
FROM information_schema.table_constraints AS table_constraint
JOIN information_schema.key_column_usage ON table_constraint.constraint_name = key_column_usage.constraint_name
JOIN information_schema.constraint_column_usage ON constraint_column_usage.constraint_name = key_column_usage.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
) foo
) bar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment