How to prevent dead locks is really good question asked by many SQL developers.
What is dead lock in database
This is called transaction contingency. Waiting of one transaction on other transaction is called deadlock.
Transaction A might hold a lock on some rows in the Accounts table and needs to update some rows in the Orders table to finish. Transaction B holds locks on those very rows in the Orders table but needs to update the rows in the Accounts table held by Transaction A. Transaction A cannot complete its transaction because of the lock on Orders. Transaction B cannot complete its transaction because of the lock on Accounts. All activity comes to a halt and remains at a standstill forever unless the DBMS detects the deadlock and aborts one of the transactions. The above figure shows this situation.
So, I am giving here the four best methods to avoid it.
- First you should not leave transactions open longer than necessary. So, you need to commit the transaction as often as possible. You must use appropriately COMMIT and ROLLBACK commands.
- You should not use higher isolation level than you really need
- The transactions that take longer time, you should schedule them separately
- You need to take care while writing SQL query that creates Deadlock