Explain foreign key constraint in MySQL
Explain foreign key constraint in MySQL
A foreign key constraint in MySQL is a type of database constraint that's used to establish a link between two tables. This constraint ensures that the relationship between the tables remains consistent. Essentially, a foreign key in one table points to a primary key in another table, creating a parent-child relationship between the two tables.
A foreign key constraint is defined on the child table and it references the primary key of the parent table. The main purpose of a foreign key constraint is to maintain referential integrity between the two tables. This means it ensures that the data referenced by the foreign key exists in the parent table, preventing orphan records and maintaining data accuracy and consistency.
When a foreign key constraint is enforced, any insert or update of the foreign key value in the child table is checked against the values in the parent table's primary key column. If the value does not exist in the parent table, the operation fails. This check ensures that all references are valid and that the integrity of the data is maintained.
The foreign key constraint can be added at the time of table creation using the CREATE TABLE
statement or to an existing table using the ALTER TABLE
statement. Here’s a basic example of how to define a foreign key constraint using the CREATE TABLE
statement:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderNumber INT NOT NULL,
UserID INT,
FOREIGN KEY (UserID) REFERENCES Users(UserID)
);
In this example, UserID
in the Orders
table is a foreign key that references the UserID
in the Users
table.
MySQL supports several referential actions that define what happens when the data referenced by a foreign key is updated or deleted. These actions include:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào