Menu

FOREIGN KEY in SQL: Why Does an INSERT Fail When the Referenced Customer Does Not Exist?
📰

FOREIGN KEY in SQL: Why Does an INSERT Fail When the Referenced Customer Does Not Exist?

DEV Community: sql·Kailas Warade·6 days ago
#S4Dxy2OB
#devtosql#devto#dev#database#sqlinterview
Long article (776 words) — no AI summary yet.
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.