Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade Delete Query

Tags:

sql

oracle

I have three tables. Product, Company, Employee

ProductId of Product table is foregin key for Company and CompanyId of Company table is foregin key for Employee

So on deleting ProductId from Product table, all the related records in other tables should delete. But I can't touch schema(can't use alter table). How should I write the query in that case..

like image 529
Nits Avatar asked Aug 27 '10 10:08

Nits


People also ask

What does cascade delete mean in SQL?

Cascade delete- a relational database term used to describe the process by which child records are automatically deleted when their parent record is deleted- is, indeed, powerful. When used intentionally and correctly, cascade delete allows you to reduce the quantity of SQL statements needed to perform delete actions.

What is on delete cascade example?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.

Is Cascade delete good practice?

Why sql server cascade delete is bad? sql server cascade delete should not cause an unexpected loss of data. If a delete requires related records to be deleted, and the user needs to know that those records are going to go away, then cascading deletes should not be used.


2 Answers

If you can't add constraints that propagates the delete, you have to write all the necessary deletes yourself:

delete employee where companyid in (select companyid from company c where productid = xxx);
delete company where productid=xxx;
delete product where productid=xxx;
like image 195
Erich Kitzmueller Avatar answered Oct 05 '22 09:10

Erich Kitzmueller


Try this option. I don't have environment to test this. I guess with some changes it should work at your end.

DELETE Product,Company,Employee 
FROM 
user LEFT JOIN items ON product.productid = company.productid 
LEFT JOIN orders ON company.productid = product.productid 
WHERE product.productid = [$productid]
like image 35
Pravin Satav Avatar answered Oct 05 '22 10:10

Pravin Satav