Imagine you are working on an e-commerce application.
Whenever a customer places an order, the database needs to store the order ID, customer ID and order date.
But there is one important rule: an order should not refer to a customer who does not exist in the database.
This is where a FOREIGN KEY constraint becomes useful.
Let's understand this with a simple SQL example.
Understanding the Customers Table
Suppose your application already has a "customers" table containing the following records:
customer_id| customer_name
101| Rahul
102| Priya
103| Amit
Here, "customer_id" uniquely identifies each customer.
Creating an Orders Table Using a FOREIGN KEY
Now, you need to create an "orders" table.
Each order should be associated with an existing customer.
You can create the table using the following SQL statement:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
);
Let's understand the important…