Explain

How can I list all foreign keys referencing a given table in SQL Server?

Use the system catalog views sys.foreign_keys, sys.foreign_key_columns, sys.columns, and sys.tables. For example:

SELECT
    fk.name AS ForeignKeyName,
    OBJECT_NAME(fk.parent_object_id) AS ReferencingTable,
    c.name AS ReferencingColumn,
    OBJECT_NAME(fk.referenced_object_id) AS ReferencedTable,
    rc.name AS ReferencedColumn
FROM sys.foreign_keys fk
JOIN sys.foreign_key_columns fkc
    ON fk.object_id = fkc.constraint_object_id
JOIN sys.columns c
    ON fkc.parent_object_id = c.object_id
    AND fkc.parent_column_id = c.column_id
JOIN sys.columns rc
    ON fkc.referenced_object_id = rc.object_id
    AND fkc.referenced_column_id = rc.column_id
WHERE OBJECT_NAME(fk.referenced_object_id) = 'YourTableName';

Replace 'YourTableName' with the table you want to check. This query displays each foreign key’s name, the referencing table/column, and the referenced table/column.

Recommended Courses

Recommended Courses

  1. Grokking Database Fundamentals for Tech Interviews

  2. Relational Database Design and Modeling for Software Engineers

  3. Grokking System Design Fundamentals