Consider these two tables:
CREATE TABLE Departments ( DeptID INT PRIMARY KEY, DeptName VARCHAR(50) ); CREATE TABLE Employees ( EmpID INT PRIMARY KEY, EmpName VARCHAR(50), DeptID INT, FOREIGN KEY (DeptID) REFERENCES Departments(DeptID) ); INSERT INTO Departments VALUES (1, 'HR'), (2, 'IT'); INSERT INTO Employees VALUES (101, 'Alice', 1), (102, 'Bob', 3);
What happens when inserting the second employee?
Foreign keys must match existing values in the referenced table.
The foreign key constraint requires that DeptID in Employees must exist in Departments. Since 3 is not in Departments, the insert fails.
Choose the correct statement about foreign key constraints in SQL.
Think about what referential integrity means.
Foreign keys ensure that values in the child table exist in the parent table, maintaining referential integrity.
Which SQL statement correctly adds a foreign key constraint to the Employees table referencing Departments?
Check the syntax for adding constraints with names.
Option D uses correct syntax: ADD CONSTRAINT with a name, then FOREIGN KEY (column) REFERENCES table(column).
You need to insert thousands of rows into a child table with a foreign key. Which approach optimizes performance?
Think about temporarily suspending checks to speed up bulk operations.
Disabling foreign key checks temporarily speeds up bulk inserts but requires care to maintain data integrity.
Given these tables:
CREATE TABLE Parents ( ParentID INT PRIMARY KEY ); CREATE TABLE Children ( ChildID INT PRIMARY KEY, ParentID INT, FOREIGN KEY (ParentID) REFERENCES Parents(ParentID) ); CREATE TABLE Grandchildren ( GrandchildID INT PRIMARY KEY, ChildID INT, FOREIGN KEY (ChildID) REFERENCES Children(ChildID) ); ALTER TABLE Grandchildren ADD CONSTRAINT fk_child FOREIGN KEY (ChildID) REFERENCES Children(ChildID);
The last ALTER TABLE statement fails. Why?
Check if the foreign key constraint already exists.
The foreign key on ChildID in Grandchildren was defined inline during table creation, so adding it again causes a duplicate constraint error.