Monday, September 7, 2026

MySQL: Find All Foreign Key Constraints in a Database

It was frustrating when I struggled to find all the foreign keys in my MySQL database. My project manager kept asking for them, so when I finally figured it out, it was a huge relief and a great moment!

While this is straightforward in MS SQL Server, doing it in MySQL can be tricky if you don't know where to look. I'm sharing this snippet here to help other developers quickly pull this information.

Run these queries in your MySQL query editor:

1. Find Foreign Keys for a Specific Schema (Database) and Table

 

SELECT 
    f.table_schema AS 'schema',
    f.table_name AS 'table',
    f.column_name AS 'column',
    f.constraint_name AS 'constraint_name',
    f.referenced_table_name AS 'referenced_table',
    f.referenced_column_name AS 'referenced_column'
FROM 
    information_schema.KEY_COLUMN_USAGE f
WHERE 
    f.table_schema = 'admin_kairali' 
    AND f.referenced_column_name IS NOT NULL; 

 

 Note: If you want to filter down to a single specific table, add AND f.table_name = 'your_table_name' to the WHERE clause.

2. Find All Foreign Keys Across the Entire Server

 
SELECT 
    f.table_schema AS 'schema',
    f.table_name AS 'table',
    f.column_name AS 'column',
    f.constraint_name AS 'constraint_name',
    f.referenced_table_name AS 'referenced_table',
    f.referenced_column_name AS 'referenced_column'
FROM 
    information_schema.KEY_COLUMN_USAGE f
WHERE 
    f.referenced_column_name IS NOT NULL;

 

 

No comments:

Post a Comment