Example of deadlock caused by Oracle foreign key not indexed

Source: Internet
Author: User

-- Create a table as a sub-table

Create table fk_t as select * from user_objects;

Delete from fk_t where object_id is null;

Commit;

-- Create a table as the parent table

Create table pk_t as select * from user_objects;

Delete from pk_t where object_id is null;

Commit;

-- Create the primary key of the parent table

Alter table PK_t add constraintpk_pktable primary key (OBJECT_ID );

-- Create a foreign key for the sub-table

Alter table FK_t addconstraint fk_fktable foreign key (OBJECT_ID) references pk_t (OBJECT_ID );

-- Session1: execute a delete operation. At this time, a Row-S (SX) Lock is added to the sub-table and parent table.

Delete from fk_t whereobject_id = 100;

Delete from Maid where object_id = 100;

-- Session2: execute another delete operation and find that the second Delete statement is waiting.

Delete from fk_t whereobject_id = 200;

Delete from pk_t whereobject_id = 200;

-- Return to session1: the deadlock occurs immediately

Delete from pk_t whereobject_id = 100;

Session2 reports the following error:

SQL> delete from Maid where object_id = 200;
Delete from pk_table where object_id = 200
*
Row 3 has an error:

ORA-00060: deadlock detected while waiting for resources

When an index is added to the foreign key column of the child table, the deadlock is eliminated because the table lock is not required to delete the parent table record.

-- Create an index for the foreign key

Create index ind_pk_object_id on fk_t (object_id) nologging;

-- Repeat the above operation session1

Delete from fk_t whereobject_id = 100;

Delete from pk_t whereobject_id = 100;

-- Session2

Delete from fk_t whereobject_id = 200;

Delete from pk_t whereobject_id = 200;

-- No deadlock will occur when session1 is returned.

Delete from pk_t whereobject_id = 100;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.