Test Foreign Key Constraint
In this step, you will test the foreign key constraint to see how it prevents invalid data from being inserted into the database.
First, insert a user into the users
table:
INSERT INTO users (id, name) VALUES (1, 'Alice');
This command inserts a new user with id
1 and name
'Alice' into the users
table.
Now, try to insert an order into the orders
table with a user_id
that does not exist in the users
table:
INSERT INTO orders (user_id, amount) VALUES (999, 100.0);
Because foreign key checks are enabled, this command will fail with an error message:
Error: FOREIGN KEY constraint failed
This demonstrates that the foreign key constraint is working correctly, preventing you from creating an order for a non-existent user.
Next, insert a valid order with the existing user_id
:
INSERT INTO orders (user_id, amount) VALUES (1, 100.0);
This command will succeed because the user_id
1 exists in the users
table.