Search code examples
sqloracleoracle12ctruncate

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.


Solution

  • 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.