/* list all the keys and relationships between the tables ----------- */ /* using a pre-built custom view */ SELECT * FROM v_key_column; /* MySQL - Without the view ---------------------------------------- */ SELECT table_name, column_name, constraint_name, ordinal_position, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage; /* Oracle - Without the view --------------------------------------- */ SELECT ucc1.table_name, ucc1.column_name, ucc1.position, uc.constraint_name, uc.constraint_type, ucc2.table_name, ucc2.column_name, ucc2.position FROM user_constraints uc JOIN user_cons_columns ucc1 ON uc.constraint_name = ucc1.constraint_name LEFT JOIN user_cons_columns ucc2 ON uc.r_constraint_name = ucc2.constraint_name WHERE uc.constraint_type IN ('P','R','U') ORDER BY 1, 4, 5, 3, 2; /* SQLite ---------------------------------------------------------- */ SELECT sql FROM sqlite_master WHERE sql LIKE '%REFERENCES%'; /* SQL Server ------------------------------------------------------ */ SELECT fk.name 'FK Name', tp.name 'Table Name', cp.name 'Column Name', tr.name 'Refrenced Table', cr.name 'Referenced Column' FROM sys.foreign_keys fk JOIN sys.tables tp ON fk.parent_object_id = tp.object_id JOIN sys.tables tr ON fk.referenced_object_id = tr.object_id JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id JOIN sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id JOIN sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id ORDER BY tp.name, cp.name