How to find whether a FOREIGN KEY is used in our SQL Database or not, Explain with some example Syntax.
To find whether a foreign key is used in your SQL database, you can use the following query:
SELECT * FROM information_schema.table_constraints WHERE constraint_type = 'FOREIGN KEY' AND table_name = 'your_table_name';
In the above query, the information_schema.table_constraints view is used to retrieve information about the foreign key constraints defined in the database. The constraint_type = ‘FOREIGN KEY’ condition filters the results to only show foreign key constraints. The table_name = ‘your_table_name’ condition specifies the name of the table you want to search for foreign keys in.
If the query returns any results, it means that there is at least one foreign key constraint defined in the table. Each row in the result set represents a foreign key constraint and includes information such as the name of the constraint, the name of the foreign key column, and the name of the referenced table and column.
For example, suppose you have a table named orders with a foreign key constraint on the customer_id column that references the customers table:
CREATE TABLE customers ( Â Â Â Â id INT PRIMARY KEY, Â Â Â Â name VARCHAR(50) ); Â CREATE TABLE orders ( Â Â Â Â id INT PRIMARY KEY, Â Â Â Â customer_id INT, Â Â Â Â FOREIGN KEY (customer_id) REFERENCES customers(id) );
To find the foreign key constraints in the orders table, you can use the following query:
SELECT *
FROM information_schema.table_constraints
WHERE constraint_type = ‘FOREIGN KEY’ AND table_name = ‘orders’;
