I have two tables
TableOne (TABLE_ONE_ID (pk), TABLE_TWO_ID (fk), ...(something else) ) TableTwo (TABLE_TWO_ID (pk), TABLE_ONE_ID (fk), ...(something else) )
How can I delete records from these tables?
P.S. I think that it is bad design, but this is not my fault and I don't have permission to change the database structure. I just need to know how to delete records from these tables.
I'm not sure of the best way to go about this but I would probably do something like:
UPDATE TableOne SET TABLE_TWO_ID = null; DELETE FROM TableTwo; DELETE FROM TableOne;
Either defer one of the foreign keys, or assign NULL (assuming it is NULL-able) to break the cycle.
BTW, how are you inserting the data? You must have done something to break the cycle there too.
NOTE: Disabling or deleting the FK may be OK if just one carefully controlled session is modifying the database, but would leave you wide open for data corruption in a concurrent environment where other clients may not be aware that the FK they expect is no longer enforced.
You can disable the foreign key with:
alter table TableOne disable constraint fk_table_two_id;
After that, you should be able to delete the rows.
Per DaveCosta's comment, you could defer the constraint checks. That way the constraints are checked over the entire transaction, not each individual SQL statement. For example:
begin transaction; set constraints all deferred; delete from TableTwo; delete from TableOne; commit transaction;