How To Create Foreign Key In SQL?

Use `FOREIGN KEY` in the `CREATE TABLE` statement

Reference the parent table column with `REFERENCES`

Ensure the referenced column is a `PRIMARY KEY` or `UNIQUE` key

Match the data type of the foreign key column with the referenced column

Example:

`CREATE TABLE orders (`

`order_id INT PRIMARY KEY,`

`customer_id INT,`

`FOREIGN KEY (customer_id) REFERENCES customers(customer_id)`

`);`

Add a foreign key to an existing table with `ALTER TABLE`

Example:

`ALTER TABLE orders`

`ADD CONSTRAINT fk_customer`

`FOREIGN KEY (customer_id) REFERENCES customers(customer_id);`

Use `ON DELETE` and `ON UPDATE` actions if needed

Example:

`FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE ON UPDATE CASCADE;`

Suggested for You

Trending Today