How to prevent database deadlocks in concurrent transactions?

How to prevent database deadlocks in concurrent transactions?

One simple solution to avoiding deadlocks is to ensure that you always lock rows in a particular order. For example, if you have a transaction that wants to update two different rows, always update the row with the smaller id first and the larger id second. If your code always does that, you at least won’t have row-level deadlocks.

How to avoid a deadlock in SQL Server?

You can avoid this specific deadlock by ensuring page-level shared locks are not taken on the same access method after the UPDLOCK statement (row-level shared locks would be ok). This will avoid the SIU page lock. The page granularity explains why operations on two different id values can deadlock.

Is there a way to repeat a deadlock in bteq?

BTEQ can repeat the step that ended in a deadlock; the error code 2631 must occur and “.SET RETRY ON” must be active. BTEQ will then repeat the request (but not the whole transaction). This functionality is not available in other client applications and must be programmed.

When does a Teradata transaction go into a deadlock?

We just described a deadlock situation. Without deadlock handling, both transactions would wait forever, or until they are aborted. On Teradata, deadlocks can happen on one AMP (local deadlock) or across different AMPs (global deadlock), and for various reasons.

When do you get a deadlock in SQL Server?

All of the documentation on SQL Server deadlocks talks about the scenario in which operation 1 locks resource A then attempts to access resource B and operation 2 locks resource B and attempts to access resource A. However, I quite often see deadlocks between a select and an update or even between multiple selects in some of our busy applications.

When do you use update lock in SQL Server?

When two transactions are waiting on each other to convert Shared locks on resources to Exclusive locks, a deadlock occurs. Update lock (U) is used to avoid deadlocks. Unlike the Exclusive lock, the Update lock places a Shared lock on a resource that already has another shared lock on it.

What happens to the second select in SQL Server?

In SQL Server, if you issue the selects with WITH (UPDLOCK), the second select will wait until the first select is finished. Otherwise they get shared locks, and when they simultaneously try to upgrade to exclusive locks, they deadlock.