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?

  1. AThe row is not added and an error occurs, because it violates the referential integrity constraint
  2. BThe row is added, and a row with cust_id 'C5' is automatically added to the customer table as well
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Database Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Database Basics questions

  1. SQL statements are divided into the data definition language (DDL), data manipulation language (DML) and data control language (DCL). Which one is classified as DDL?
  2. A product table has five rows of (name, price): (pen, 120), (notebook, 250), (eraser, 80), (file, 300), (ruler, 150). Which shows, in order, the rows returned by SELECT name FROM product WHERE price >= 150 ORDER BY price DESC?
  3. The dept column of an employee table contains, from the top row down, Sales, Dev, Sales, Admin, Dev, Sales (six rows in total). How many rows does SELECT DISTINCT dept FROM employee return?
  4. What is the result of executing DELETE FROM employee in SQL without a WHERE clause?
  5. The score column of an exam table contains four values: 80, NULL, 70, 90 (NULL means the person did not take the exam). What is the result of SELECT AVG(score) FROM exam?