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

What is FOREIGN KEY ?

Câu trả lời

A foreign key is a column or a set of columns in a database table that establishes a link between data in two tables. It is used to enforce referential integrity within the database. Specifically, a foreign key in one table points to a primary key in another table, creating a parent-child relationship between the tables.

Key Characteristics of a Foreign Key:

  1. Linking Tables: A foreign key links two tables together by referencing the primary key of another table. The table containing the foreign key is called the child table, and the table with the primary key is called the parent table[1][2][3][4][5].
  2. Data Integrity: Foreign keys ensure that the data in the child table corresponds to valid data in the parent table. This prevents invalid data from being inserted into the foreign key column, as it must match an existing value in the parent table[1][4][5].
  3. Constraints: Foreign key constraints can be used to enforce rules on the data, such as preventing the deletion of a record in the parent table if it is referenced by a record in the child table. These constraints help maintain the consistency and integrity of the data across the database[1][2][3][5].
  4. Multiple Foreign Keys: A table can have more than one foreign key, each linking to different parent tables. This allows for complex relationships and data structures within the database[1][3][5].
  5. Null Values: Foreign key columns can accept null values, which means that a record in the child table does not necessarily have to reference a record in the parent table[1][6].

Example:

Consider two tables, Customers and Orders. The Customers table has a primary key CustomerID, and the Orders table has a foreign key CustomerID that references the CustomerID in the Customers table.

sql Copy
CREATE TABLE Customers (
    CustomerID int PRIMARY KEY,
    Name varchar(100),
    Age int
);

CREATE TABLE Orders (
    OrderID int PRIMARY KEY,
    OrderDate date,
    CustomerID int,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

In this example, the CustomerID column in the Orders table is a foreign key that references the CustomerID column in the `...

middle

middle

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

middle

Discuss INNER JOIN ON vs WHERE clause (with multiple FROM tables)

middle

What is the difference between INNER JOIN and OUTER JOIN ?

middle

What’s the difference between Azure SQL Database and Azure SQL Managed Instance?

Bình luận

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

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