Open In App

Can a Composite Key be a Foreign Key in Another Table?

Last Updated : 27 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Answer: Yes, a composite key can be used as a foreign key in another table within a relational database.

In SQL databases, a composite key comprises multiple columns to uniquely identify rows in a table. To establish a foreign key referencing a composite key:

Create the Parent Table

Define the parent table with a composite key.

CREATE TABLE ParentTable (
Column1 datatype1,
Column2 datatype2,
PRIMARY KEY (Column1, Column2)
);

Define the Child Table

Create the child table with matching data types and a foreign key referencing the composite key.

CREATE TABLE ChildTable (
ForeignKeyCol1 datatype1,
ForeignKeyCol2 datatype2,
OtherColumns datatype3,
FOREIGN KEY (ForeignKeyCol1, ForeignKeyCol2)
REFERENCES ParentTable(Column1, Column2)
);

This setup establishes referential integrity between the child and parent tables. The foreign key in the child table aligns with the composite key in the parent table, ensuring data consistency and relational integrity.

Conclusion

Establishing foreign keys referencing composite keys ensures robust relational integrity in a database. This practice maintains data consistency across tables, facilitating efficient data management and enhancing the overall integrity and reliability of the database structure.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads