Insert Data and Test the Foreign Key Constraint
In this step, you will insert data into the customers and orders tables and test the foreign key constraint.
First, you need to enable foreign key constraints in SQLite (they are disabled by default):
PRAGMA foreign_keys = ON;
Now, insert some data into the customers table:
INSERT INTO customers (first_name, last_name, email) VALUES
('John', 'Doe', 'john.doe@example.com'),
('Jane', 'Smith', 'jane.smith@example.com');
This command inserts two new customers into the customers table. The customer_id will be automatically assigned.
Now, insert an order into the orders table, referencing one of the existing customers:
INSERT INTO orders (customer_id, order_date, total) VALUES
(1, '2023-01-01', 100.00);
This command inserts a new order into the orders table, associating it with the customer whose customer_id is 1.
Next, try to insert an order with a customer_id that does not exist in the customers table:
INSERT INTO orders (customer_id, order_date, total) VALUES
(99, '2023-01-02', 50.00);
You will see an error message similar to this: Error: FOREIGN KEY constraint failed. This confirms that the foreign key constraint is working correctly, preventing you from creating an order for a non-existent customer.
To view the data in the tables, you can use the following commands:
SELECT * FROM customers;
SELECT * FROM orders;
These commands will display the contents of the customers and orders tables, respectively.