How to add 'ON DELETE CASCADE' in ALTER TABLE statement - sql

I have a foreign key constraint in my table, I want to add ON DELETE CASCADE to it.
I have tried this:
alter table child_table_name
modify constraint fk_name
foreign key (child_column_name)
references parent_table_name (parent_column_name) on delete cascade;
Doesn't work.
EDIT:
Foreign key already exists, there are data in foreign key column.
The error message I get after executing the statement:
ORA-02275: such a referential constraint already exists in the table

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

First drop your foreign key and try your above command, put add constraint instead of modify constraint.
Now this is the command:
ALTER TABLE child_table_name
ADD CONSTRAINT fk_name
FOREIGN KEY (child_column_name)
REFERENCES parent_table_name(parent_column_name)
ON DELETE CASCADE;

As explained before:
ALTER TABLE TABLENAME
drop CONSTRAINT FK_CONSTRAINTNAME;
ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
FOREIGN KEY (FId)
REFERENCES OTHERTABLE
(Id)
ON DELETE CASCADE ON UPDATE NO ACTION;
As you can see those have to be separated commands, first dropping then adding.

Answer for MYSQL USERS:
ALTER TABLE ChildTableName
DROP FOREIGN KEY `fk_table`;
ALTER TABLE ChildTableName
ADD CONSTRAINT `fk_t1_t2_tt`
FOREIGN KEY (`parentTable`)
REFERENCES parentTable (`columnName`)
ON DELETE CASCADE
ON UPDATE CASCADE;

This PL*SQL will write to DBMS_OUTPUT a script that will drop each constraint that does not have delete cascade and recreate it with delete cascade.
NOTE: running the output of this script is AT YOUR OWN RISK. Best to read over the resulting script and edit it before executing it.
DECLARE
CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
select * from user_cons_columns
where constraint_name = theCons and owner = theOwner
order by position;
firstCol BOOLEAN := TRUE;
begin
-- For each constraint
FOR cons IN (select * from user_constraints
where delete_rule = 'NO ACTION'
and constraint_name not like '%MODIFIED_BY_FK' -- these constraints we do not want delete cascade
and constraint_name not like '%CREATED_BY_FK'
order by table_name)
LOOP
-- Drop the constraint
DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
-- Re-create the constraint
DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME
|| ' FOREIGN KEY (');
firstCol := TRUE;
-- For each referencing column
FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
LOOP
IF(firstCol) THEN
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT(') REFERENCES ');
firstCol := TRUE;
-- For each referenced column
FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
LOOP
IF(firstCol) THEN
DBMS_OUTPUT.PUT(consCol.OWNER);
DBMS_OUTPUT.PUT('.');
DBMS_OUTPUT.PUT(consCol.TABLE_NAME); -- This seems a bit of a kluge.
DBMS_OUTPUT.PUT(' (');
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT_LINE(') ON DELETE CASCADE ENABLE VALIDATE;');
END LOOP;
end;

Here is an handy solution!
I'm using SQL Server 2008 R2.
As you want to modify the FK constraint by adding ON DELETE/UPDATE CASCADE, follow these steps:
NUMBER 1:
Right click on the constraint and click to Modify
NUMBER 2:
Choose your constraint on the left side (if there are more than one). Then on the right side, collapse "INSERT And UPDATE Specification" point and specify the actions on Delete Rule or Update Rule row to suit your need. After that, close the dialog box.
NUMBER 3:
The final step is to save theses modifications (of course!)
PS: It's saved me from a bunch of work as I want to modify a primary key referenced in another table.

For anyone using MySQL:
If you head into your PHPMYADMIN webpage and navigate to the table that has the foreign key you want to update, all you have to do is click the Relational view located in the Structure tab and change the On delete select menu option to Cascade.
Image shown below:

If you want to change a foreign key without dropping it you can do:
ALTER TABLE child_table_name WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE

for postgresql
BEGIN TRANSACTION ;
ALTER TABLE bank_accounts
DROP CONSTRAINT bank_accounts_company_id_fkey;
ALTER TABLE bank_accounts
ADD CONSTRAINT bank_accounts_company_id_fkey FOREIGN KEY (company_id)
REFERENCES companies (id)
ON DELETE CASCADE;
END;

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`)
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

MySQL workbench img
Right click at the table you want to alter and click alter table, then click Foreign Keys. You can see Foreign Keys Options on the right side and just select cascade and click apply!

Related

Oracle Truncate Parent table constraint error

Parent table A with some records.
Child table B with 0 records.
I have a cursor to do truncation on these tables in reverse tree order (i.e. truncate child first, then parent)
But I'm still getting this error when I truncate the parent table 'ORA-02266: unique/primary keys in table referenced by enabled foreign keys' error, despite the fact that the child table has no records at all.
However, when I do 'Delete from ' in the same order, all constraint related errors were avoided. And 'Delete from' takes really long time to run.
I don't want to disable or drop any constraints.
However, when I do 'Delete from ' in the same order, all constraint related errors were avoided.
That's the only way if you have constraints enabled. You cannot truncate. If you still want to truncate the table, then you could find the constraint name from user_constraints, and then DISABLE them:
ALTER TABLE table_name DISABLE CONSTRAINT constraint_name;
Then you could TRUNCATE the table, and re-enable the constraint:
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;
If your table has ON DELETE CASCADE option, then from Oracle 12.1 onward, you could use:
TRUNCATE TABLE table_name CASCADE;
Note, both the DELETE CASCADE and the TRUNCATE CASCADE will fail if any of the relationships in the hierarchy are not defined with the ON DELETE CASCADE clause.
There are three ways to delete from parent/child tables:
CREATE TABLE par (i NUMBER CONSTRAINT par_pk PRIMARY KEY);
CREATE TABLE chi (i NUMBER CONSTRAINT chi_fk REFERENCES par(i) ON DELETE CASCADE);
INSERT INTO par VALUES(1);
INSERT INTO chi VALUES(1);
1) If you have Oracle 12 or later, and you have foreign keys with ON DELETE CASCADE, you can use TRUNCATE CASCADE, which I expect to be the fastest option:
TRUNCATE TABLE par CASCADE;
Table PAR truncated.
SELECT count(*) FROM par;
0
SELECT count(*) FROM chi;
0
2) If your foreign keys are defined with ON DELETE CASCADE, you can use DELETE, which I expect to be the slowest option:
DELETE FROM par;
1 row deleted.
SELECT count(*) FROM par;
0
SELECT count(*) FROM chi;
0
3) Otherwise, you can disable the foreign keys, truncate the tables and reenable the foreign keys. This is fast, but is a little bit more risky than the other options (please check that the constraints are all valid afterwards):
ALTER TABLE chi DISABLE CONSTRAINT chi_fk;
TRUNCATE TABLE chi;
TRUNCATE TABLE par;
ALTER TABLE chi ENABLE CONSTRAINT chi_fk;
AFAIK, it is not possible to alter a foreign key from normal to ON DELETE CASCADE. I guess you have to drop and recreate them:
ALTER TABLE chi DROP CONSTRAINT chi_fk;
ALTER TABLE chi ADD CONSTRAINT chi_fk REFERENCES par(i) ON DELETE CASCADE;

SQL Check if a "CHECK CONSTRAINT" has been ran?

Should the second ALTER TABLE CHECK CONSTRAINT be in an IF (NOT) EXISTS so that the script can be executed repeatedly?
IF NOT EXISTS (
SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_NAME ='fk_RoleId'
)
BEGIN
ALTER TABLE [dbo].[webpages_UsersInRoles] WITH CHECK ADD CONSTRAINT [fk_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[webpages_Roles] ([RoleId])
END
GO
-- Put me in an IF ... () BEGIN ... END?
ALTER TABLE [dbo].[webpages_UsersInRoles] CHECK CONSTRAINT [fk_RoleId]
GO
It doesn't cause any errors, but if it should be in an IF clause, how do you test if it has been ran (what can the if contain)?
If you do want a check (it's not necessary), sys.foreign_keys has a column is_not_trusted:
FOREIGN KEY constraint has not been verified by the system.

Combining 3 steps into one SQL script

I'm pretty new to SQL, so it sould be rather easy to answer my questions.
Here is what I want to do:
Deactivate constraints:
Deactivate constraints in the database:
begin
for cur in (select fk.owner, fk.constraint_name , fk.table_name
from all_constraints fk, all_constraints pk
where fk.CONSTRAINT_TYPE = 'R' and
pk.owner = 'USER1' and
fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME ) loop
execute immediate 'ALTER TABLE '||cur.owner||'.'||cur.table_name||' MODIFY CONSTRAINT '||cur.constraint_name||' DISABLE';
end loop;
end;
Delete from tables:
delete from USER_TEST.Table1;
delete from USER_TEST.Table2;
delete from USER_TEST.Table3;
Reactivate Constraints:
begin
for cur in (select fk.owner, fk.constraint_name , fk.table_name
from all_constraints fk, all_constraints pk
where fk.CONSTRAINT_TYPE = 'R' and
pk.owner = 'USER1' and
fk.R_CONSTRAINT_NAME = pk.CONSTRAINT_NAME ) loop
execute immediate 'ALTER TABLE '||cur.owner||'.'||cur.table_name||' MODIFY CONSTRAINT '||cur.constraint_name||' ENABLE NOVALIDATE';
end loop;
end;
Does anyone know how to combine these steps into one .sql script so I can run this on Oracle SQLDeveloper? Or maybe a more elegant way to perform the deletion from the tables?
I'd be very thankful
If it is just about deleting from tables which have foreign keys to each other, you can always delete in constraint order ("children first"). Then you won't have to mess with your constraints at all. Don't forget to commit at the end.
If it is about speed, then you may want to disable constraints and empty the tables via TRUNCATE rather then DELETE. You should however, not delete ALL constraints of the schema, but just the foreign keys of the affected tables which point to another affected table. This will prevent you from shooting into your foot. You can to this without looping, just disable the constraints explicitly. E
So the entire script should look like this
Alter Table User_test.Table1 Modify Constraint FK... Disable;
Alter Table User_test.Table2 Modify Constraint FK... Disable;
...
Trunacte Table user_test.Table1;
Trunacte Table user_test.Table2;
...
Alter Table User_test.Table1 Modify Constraint FK... Enable;
Alter Table User_test.Table2 Modify Constraint FK... Enable;
...

Truncate table in Oracle getting errors

I got the problem is when I run following command in Oracle, I encounter the error.
Truncate table mytable;
Errors:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
I found that, this mytable has relationship with other tables. That's why Truncate command cannot proceed anymore. How to delete data from myTable with the SQL scripts using Truncate command?
You have to swap the TRUNCATE statement to DELETE statements, slower and logged but that's the way to do it when constraints are in place.
DELETE mytablename;
Either that or you can find the foreign keys that are referencing the table in question and disable them temporarily.
select 'ALTER TABLE '||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME||';'
from user_constraints
where R_CONSTRAINT_NAME='<pk-of-table>';
Where pk-of-table is the name of the primary key of the table being truncated
Run the output of the above query. When this has been done, remember to enable them again, just change DISABLE CONSTRAINT into ENABLE CONSTRAINT
this page offers a very good solution ...
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
I'm here copying from it the Solution:
Find the referenced ENABLED foreign key constraints and disable them.
truncate/delete from the table .
using any text editor .. just change disable to enable in the output you get from the query , then run it.
select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
from all_constraints a, all_constraints b
where a.constraint_type = 'R' and a.status='ENABLED'
and a.r_constraint_name = b.constraint_name
and a.r_owner = b.owner
and b.table_name = upper('YOUR_TABLE');
The error message is telling you that there are other table(s) with a foreign key constraint referring to your table.
According to the Oracle docs
You cannot truncate the parent table
of an enabled foreign key constraint.
You must disable the constraint before
truncating the table.
The syntax for disabling a foreign key is:
ALTER TABLE table_name disable
CONSTRAINT constraint_name;
Issue:
Error “ORA-02266: unique/primary keys in table referenced by enabled foreign keys” when trying to truncate a table.
Error Message:
SQL> truncate table TABLE_NAME;
truncate table TABLE_NAME
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
Solution:
-- Find the referenced foreign key constraints.
SQL> select 'alter table '||a.owner||'.'||a.table_name||' disable constraint '||a.constraint_name||';'
2 from all_constraints a, all_constraints b
3 where a.constraint_type = 'R'
4 and a.r_constraint_name = b.constraint_name
5 and a.r_owner = b.owner
6 and b.table_name = 'TABLE_NAME';
'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'DISABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
---------------------------------------------------------------------------------------------------------
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
-- Disable them
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT disable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION disable constraint CONSTRAINT_NAME;
-- Run the truncate
SQL> truncate table TABLE_NAME;
Table truncated.
-- Enable the foreign keys back
SQL> select 'alter table '||a.owner||'.'||a.table_name||' enable constraint '||a.constraint_name||';'
2 from all_constraints a, all_constraints b
3 where a.constraint_type = 'R'
4 and a.r_constraint_name = b.constraint_name
5 and a.r_owner = b.owner
6 and b.table_name = 'TABLE_NAME';
'ALTER TABLE'||A.OWNER||'.'||A.TABLE_NAME||'ENABLE CONSTRAINT'||A.CONSTRAINT_NAME||';'
--------------------------------------------------------------------------------
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
-- Enable them
alter table SCHEMA_NAME.TABLE_NAME_ATTACHMENT enable constraint CONSTRAINT_NAME;
alter table SCHEMA_NAME.TABLE_NAME_LOCATION enable constraint CONSTRAINT_NAME;
Oracle 12c introduced a feature to truncate a table that is a parent of a referential integrity constraint having ON DELETE rule.
Instead of truncate table tablename; use:
TRUNCATE TABLE tablename CASCADE;
From Oracle truncate table documentation:
If you specify CASCADE, then Oracle Database truncates all child tables that reference table with an enabled ON DELETE CASCADE referential constraint. This is a recursive operation that will truncate all child tables, granchild tables, and so on, using the specified options.
A typical approach to delete many rows with many constraints is as follows:
create mytable_new with all the columns but without constrains (or create constraints disabled);
copy whatever data you need from mytable to mytable_new.
enable constraints on mytable_new to see that everything is ok.
alter any constraints that reference mytable to reference mytable_new instead and see that everything is ok.
drop table mytable.
alter table mytable_new rename to mytable.
It's far faster than deleting a million records with many slow constraints.
I had the similar issue and I sorted it out by the following scripts.
begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
and a.constraint_type not in 'P')
LOOP
execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';
end loop;
end;
/
truncate table TABLE_1;
truncate table TABLE_2;
begin
for i in (select constraint_name, table_name from user_constraints a where a.owner='OWNER' and a.table_name not in
(select b.table_name from user_constraints b where b.table_name like '%BIN%')
and a.constraint_type not in 'P')
LOOP
execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';
end loop;
end;
/
This script will first disable all the Constraints. Truncates the data in the tables and then enable the contraints.
Hope it helps.
cheers..
TRUNCATE TABLE TEST2 DROP ALL STORAGE;
This statement Actually works when there is an foreign key constraint applied on a .table
As mentioned by the error message, you cannot truncate a table that is referenced by enabled foreign keys. If you really want to use the truncate DDL command, disable the foreign key constraint first, run the truncate command, and enable it back.
Reference: Difference between TRUNCATE, DELETE and DROP commands

Stop invalid data in a attribute with foreign key constraint using triggers?

How to specify a trigger which checks if the data inserted into a tables foreign key attribute, actually exists in the references table. If it exist no action should be performed , else the trigger should delete the inserted tuple.
Eg: Consider have 2 tables
R(A int Primary Key) and
S(B int Primary Key , A int Foreign Key References R(A) ) .
I have written a trigger like this :
Create Trigger DelS
BEFORE INSERT ON S
FOR EACH ROW
BEGIN
Delete FROM S where New.A <> ( Select * from R;) );
End;
I am sure I am making a mistake while specifying the inner sub query within the Begin and end Blocks of the trigger. My question is how do I make such a trigger ?
Wouldn't a foreign key constraint better achieve what you want?
ALTER TABLE [dbo].[TABLE2] WITH CHECK
ADD CONSTRAINT [FK_TABLE2_TABLE1] FOREIGN KEY([FK_COLUMN])
REFERENCES [dbo].[TABLE1] ([PK_COLUMN])
GO
This is what foreign key constraints are meant to do - specifically, not allow a record to be inserted that violate the foreign key relationship.
Note that to make this example more readable, I used different column and table names - S, A, R and B looked like a mess.