Câu hỏi phỏng vấn MySQL
Câu hỏi

Explain foreign key constraint in MySQL

Câu trả lời

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.

Definition and Purpose

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.

How It Works

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.

SQL Syntax

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:

sql Copy
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.

Referential Actions

MySQL supports several referential actions that define what happens when the data referenced by a foreign key is updated or deleted. These actions include:

  • CASCADE: Automatically update or delet...
junior

junior

Gợi ý câu hỏi phỏng vấn

expert

What is difference between horizontal and vertical partitioning? Does MySQL support both horizontal
and vertical partitioning?

middle

What are different TEXT data types in MySQL. What is difference between TEXT and VARCHAR ?

middle

What is the use of IN and BETWEEN in MySQL queries?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào