In SQL I have:
CREATE TABLE Customer(
cust_id INT NOT NULL PRIMARY KEY CHECK (cust_id > 0),
full_name TEXT NOT NULL,
phone TEXT NOT NULL,
address TEXT NOT NULL CHECK (LENGTH(address) >= 3)
);
CREATE TABLE "Order"(
order_id INT NOT NULL PRIMARY KEY CHECK (order_id > 0),
date TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL
);
CREATE TABLE Dish(
dish_id INT NOT NULL PRIMARY KEY CHECK (dish_id > 0),
name TEXT NOT NULL CHECK (LENGTH(name) >= 3),
price NUMERIC NOT NULL CHECK (price > 0),
is_active BOOLEAN NOT NULL
);
CREATE TABLE Placed(
order_id INT NOT NULL PRIMARY KEY CHECK (order_id > 0),
cust_id INT NOT NULL CHECK (cust_id > 0),
FOREIGN KEY (order_id) REFERENCES "Order" (order_id) ON DELETE CASCADE,
FOREIGN KEY (cust_id) REFERENCES Customer (cust_id)
);
When trying to delete a customer I want to delete his personal data but to keep his placed orders and not to delete them.
When trying to run:
DELETE FROM Customer WHERE cust_id = 1
I get:
update or delete on table "customer" violates foreign key constraint "placed_cust_id_fkey" on table "placed"
DETAIL: Key (cust_id)=(1) is still referenced from table "placed".
How can I fix this?
2
Answers
You can not (and should not) delete customers from database, because the
Placed
table linked toCustomer
by foreign key. I can to advice you SOFT DELETE pattern in this case. It demand to adddeleted_at
column onCustomer
table and using this column you can mark a customer as deleted intead delete it from database.You can try this concept here
Do it with two Commands.
Soft deliting is a clean way, but because of the laws for example in Europe, you need to hard delete it.