Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Constraints Temporarily

Tags:

database

mysql

I have many tables with relationship constraints. Tables contain full of dummy data, i would like to truncate/empty the data from the tables while keeping the structure.

Everytime i want to empty a table, i get foreign key constraint errors. What can i do to disable the constraint temporarily and then set enable it back once dummy data are deleted.

I tried this solution, but didn't work! Once i disable, then try to truncate, i get fk constraint error...

//disable
SET FOREIGN_KEY_CHECKS = 0;


//enable
SET FOREIGN_KEY_CHECKS = 1;

I'm using MySQL.

Any idea?

like image 748
user311509 Avatar asked Dec 16 '11 20:12

user311509


People also ask

How temporarily disable constraints in SQL?

Use SQL Server Management StudioIn Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu. Select Close.

How temporarily disable constraints in Oracle?

There are multiple ways to disable constraints in Oracle. constraint_name; Another way to enable and disable constraints in Oracle would be to either use a plsql block or write a script. Execute Immediate 'alter table '||:tab_name||' disable constraint '||tabCons(numCount);

What is enable and disable constraints in Oracle?

You can use the ALTER TABLE statement to enable, disable, modify, or drop a constraint. When the database is using a UNIQUE or PRIMARY KEY index to enforce a constraint, and constraints associated with that index are dropped or disabled, the index is dropped, unless you specify otherwise.


2 Answers

You have to remove the FK if you want to use truncate, as truncate not a logged operation.

Can use delete with FK in place but delete is a logged operation and takes longer.

like image 157
Eric Avatar answered Oct 16 '22 20:10

Eric


Start at the end (tables that are only FK) and not referenced BY any other tales. Those you can truncate. Then work your way up and delete. If you truncate / delete in the proper order then you will not violate the contraints. Or you could drop all the constaints. Truncate the tables. Then add the contraints back in.

like image 27
paparazzo Avatar answered Oct 16 '22 20:10

paparazzo