DEV Community

Cover image for ๐Ÿ” How to Find Foreign Keys Referencing the users Table in MySQL
Tahsin Abrar
Tahsin Abrar

Posted on • Edited on

๐Ÿ” How to Find Foreign Keys Referencing the users Table in MySQL

๐Ÿงฉ The Real-World Problem

Imagine this:
A development team is handed a large, inherited MySQL database โ€” over 100 tables, minimal documentation, and one critical task at hand:

Find all tables that are related to the users table so that deleting a user doesnโ€™t leave behind orphaned records.

This often happens during data cleanup, GDPR compliance, or when building cascade delete workflows. Manually scanning through all migration files or schema definitions isnโ€™t just tedious โ€” itโ€™s prone to errors and doesnโ€™t scale.

So whatโ€™s a clean, reliable way to get this done?


๐Ÿ’ก The SQL Query That Solves It

Hereโ€™s a powerful query that pinpoints all foreign key relationships targeting the id field of the users table:

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'users'
  AND REFERENCED_COLUMN_NAME = 'id';
Enter fullscreen mode Exit fullscreen mode

โœ… What This Query Does:

  • Searches the entire database for foreign key relationships
  • Filters results to only those that reference users.id
  • Outputs exactly which table and column creates that link

๐Ÿ“Š Sample Output

For example, if the database has tables like:

  • posts with a user_id column
  • comments with an author_id column
  • orders with a user_id column

The output would resemble:

TABLE_NAME COLUMN_NAME CONSTRAINT_NAME REFERENCED_TABLE_NAME REFERENCED_COLUMN_NAME
posts user_id fk_posts_user users id
comments author_id fk_comments_user users id
orders user_id fk_orders_user users id

This gives an instant overview of all tables referencing the users table โ€” no guesswork needed.


๐Ÿ› ๏ธ Use Case: Safe User Deletion Workflow

In many real-world applications, especially SaaS systems or e-commerce platforms, deleting a user must also clean up related data such as:

  • Posts or content they created
  • Orders they placed
  • Comments or messages they wrote

Once the referencing tables are identified, developers can:

  1. Apply ON DELETE CASCADE where logical and safe
  2. Manually delete child records in the correct order
  3. Audit and log user-related records before deletion for traceability

Top comments (0)