How can I check the existing FOREIGN KEY?

Suppose I have two tables: state_list and country_list. In the state_list table, we have three columns: stateID, statename, and countryID. On the other side, I have two columns in the country_list table: countryID and countryname.

To check if the countryID column in the state_list table is a foreign key referencing the countryID primary key column in the country_list table, you can use the following SQL query:

SHOW CREATE TABLE state_list;

This query will display the complete table definition for the state_list table, including any foreign key constraints. Look for the definition of the countryID column to see if it includes a foreign key constraint referencing the countryID column in the country_list table.

If you prefer to specifically check if countryID is a foreign key, you can use the following query:

SELECT
  CONSTRAINT_NAME,
  COLUMN_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  TABLE_SCHEMA = 'your_database_name'
  AND TABLE_NAME = 'state_list'
  AND COLUMN_NAME = 'countryID'
  AND CONSTRAINT_NAME LIKE 'fk%';

Replace 'your_database_name' with the name of your database. This query retrieves information about foreign key constraints on the countryID column in the state_list table. If the countryID column has a foreign key constraint, it will be listed in the result set.

Suppose I have two tables: state_list and country_list. In the state_list table, we have three columns: stateID, statename, and countryID. On the other side, I have two columns in the country_list table: countryID and countryname. To check if the countryID column in the state_list table is a foreign key referencing the countryID primary key column…

Leave a Reply

Your email address will not be published. Required fields are marked *