Database Basics
The primary key of a customer table (cust_id, name) is cust_id, and cust_id in an orders table (order_id, cust_id) is defined as a foreign key referring to cust_id in the customer table. The customer table contains only the rows with cust_id 'C1' and 'C2'. What happens when INSERT INTO orders VALUES ('O9', 'C5') is executed in this state?
- AThe row is not added and an error occurs, because it violates the referential integrity constraint
- BThe row is added, and a row with cust_id 'C5' is automatically added to the customer table as well
- CThe row is added, but its cust_id value is replaced with NULL
Show answer and explanation
Answer: A. The row is not added and an error occurs, because it violates the referential integrity constraint
A foreign key is a column that refers to the primary key (or similar) of another table, here the customer table, and it enforces the referential integrity constraint: only values that exist in the referenced table, or NULL, may be stored. The customer table has no customer 'C5', so the DBMS rejects the attempt to add an order for a nonexistent customer, and an error occurs. This prevents orders that belong to no known customer. Conversely, an attempt to delete a customer row that still has orders is also rejected under the default behavior (NO ACTION). Adding ON DELETE CASCADE to the foreign key definition makes deleting a customer also delete that customer's orders in a cascade.
- A. Correct. A row referring to a nonexistent cust_id is rejected by the referential integrity constraint.
- B. The DBMS does not create referenced rows automatically.
- C. The DBMS does not silently replace the foreign key value with NULL; the operation fails with an error.