Bird
0
0

Given these tables:

medium📝 query result Q13 of 15
SQL - Table Relationships
Given these tables:
CREATE TABLE Authors (AuthorID INT PRIMARY KEY, Name VARCHAR(50));
CREATE TABLE Books (BookID INT PRIMARY KEY, Title VARCHAR(100), AuthorID INT, FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID));
What happens if you try to insert INSERT INTO Books (BookID, Title, AuthorID) VALUES (1, 'My Book', 99); when there is no author with AuthorID = 99 in Authors?
AThe insert succeeds but AuthorID is set to NULL
BThe insert fails due to foreign key constraint violation
CThe database creates a new author with AuthorID 99 automatically
DThe insert succeeds and adds the book
Step-by-Step Solution
Solution:
  1. Step 1: Understand foreign key constraint behavior

    A foreign key requires that the referenced value exists in the parent table to maintain data integrity.
  2. Step 2: Apply this to the insert statement

    Since AuthorID 99 does not exist in Authors, the insert violates the foreign key constraint and fails.
  3. Final Answer:

    The insert fails due to foreign key constraint violation -> Option B
  4. Quick Check:

    Foreign key requires existing parent row = D [OK]
Quick Trick: Foreign key insert fails if parent key missing [OK]
Common Mistakes:
MISTAKES
  • Assuming automatic creation of missing parent rows
  • Thinking insert will succeed with NULL foreign key
  • Ignoring foreign key constraints

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes