
How To Add Foreign Key In Sql in SQL
How to Add a Foreign Key in SQL
A Foreign Key links a column (or columns) in one table to the Primary Key of another table to enforce referential integrity.
1. Add Foreign Key When Creating a Table
CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATE, CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id));
2. Add Foreign Key to an Existing Table
Syntax:
ALTER TABLE child_tableADD CONSTRAINT constraint_name FOREIGN KEY (column_name)REFERENCES parent_table(parent_column);
Example:
ALTER TABLE ordersADD CONSTRAINT fk_customer FOREIGN KEY (customer_id)REFERENCES customers(customer_id);
Notes:
The foreign key column(s) must have the same data type as the referenced primary key column(s).
The parent table must exist before you create the foreign key.
You can add ON DELETE or ON UPDATE actions:
ALTER TABLE ordersADD CONSTRAINT fk_customer FOREIGN KEY (customer_id)REFERENCES customers(customer_id)ON DELETE CASCADEON UPDATE CASCADE;
If you want the syntax for a specific SQL dialect or more examples, just let me know!