Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a Primary Key Without Affecting Foreign Key Constrain to Other Table

Tags:

mysql

I want to delete a record from a school table without affecting a foreign key to the department name. I tried but I got this message:

"Cannot delete or update a parent row: a foreign key constraint fails (arusms.department, CONSTRAINT department_ibfk_1 FOREIGN KEY (school_name) REFERENCES school (school_name) ON UPDATE CASCADE)"

like image 482
Antweny Sawe Avatar asked Apr 19 '12 16:04

Antweny Sawe


People also ask

What happens to foreign key when primary key is deleted?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.

Can we delete primary key from a table without deleting foreign key?

We can remove PRIMARY KEY constraint from a column of an existing table by using DROP keyword along with ALTER TABLE statement.

Can we delete primary key and foreign key records?

If you have the foreign key define, you would not be able to delete the parent record, untill you delete its child. So first you have to delete the child data and then only you can delete data from main table.

Can you drop a table if its primary key is used in a foreign key constraint?

In SQL Server, you cannot drop a table if it is referenced by a FOREIGN KEY constraint. You have to either drop the child tables before removing the parent table, or remove foreign key constraints.


2 Answers

I'm not sure why you would want to do that. If you delete the school, the department will be orphaned. That's the point of having foreign keys in the first place, to enforce referential integrity. If you want the department to remain and to be able to do this, you will need to alter the foreign key to include ON DELETE SET NULL. Otherwise, you will have to drop the constraint, perform the delete, and recreate the constraint.

like image 101
mdoyle Avatar answered Oct 16 '22 22:10

mdoyle


Your error message is hiding the real cause.

(
arusms.department, 

CONSTRAINT department_ibfk_1 
  FOREIGN KEY (school_name) 
  REFERENCES school (school_name) 
  ON UPDATE CASCADE
)

When you created the foreign key constarint, you omitted the ON DELETE part. MySQL used the default action for this, which is ON DELETE RESTRICT. See the MySQL docs: FOREIGN KEY Constraints

If you want to be able to delete schools without cascading effect to the related departments, you can either

  • remove the FK constraint or

  • make the column (department.school_name) nullable and alter the constraint to have the ON DELETE SET NULL action.

If you want to be able to delete schools and cascading deleting the related departments, you can

  • alter the constraint to have the ON DELETE CASCADE action.
like image 38
ypercubeᵀᴹ Avatar answered Oct 16 '22 21:10

ypercubeᵀᴹ