Search⌘ K

Answer: The FOREIGN KEY Constraint

Explore how to apply the FOREIGN KEY constraint in SQL to maintain referential integrity between tables. Learn to modify existing tables, set foreign keys with REFERENCES, and manage constraints effectively through examples and quizzes.

Solution

The solution is given below:

MySQL
/* Modifying the EmpID in the Skills table to be NOT NULL */
ALTER TABLE Skills
MODIFY COLUMN EmpID INT NOT NULL;
/* Adding the foreign key constraint on EmpID in the Skills table */
ALTER TABLE Skills
ADD FOREIGN KEY (EmpID) REFERENCES Employees (EmpID);
/* Describe the structure of the table */
DESC Skills;

Explanation

The explanation of the solution code is given below:

  • Lines 2–3: The ALTER TABLE statement makes changes in the structure of the Skills table. It modifies the EmpID column to be NOT NULL. A NULL value in this column can lead to orphaned rows, which can cause inconsistency and data integrity issues.

  • Lines 6–7: The ALTER TABLE statement makes changes in the structure of the Skills table. It sets the EmpID column in the ...