w3resource

Effective Deadlock Handling in SQL Transactions


Handling Deadlocks Gracefully

Write a SQL query to handle deadlocks using error handling techniques.

Solution:

BEGIN TRY
    BEGIN TRANSACTION;

    -- Update conflicting rows.
    UPDATE TableA SET Column1 = 'Value1' WHERE ID = 1;
    WAITFOR DELAY '00:00:05';
    UPDATE TableB SET Column2 = 'Value2' WHERE ID = 2;

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    -- Rollback and log the deadlock error.
    ROLLBACK TRANSACTION;
    PRINT 'Deadlock detected: ' + ERROR_MESSAGE();
END CATCH;

Explanation:

  • Purpose of the Query :
    • The goal is to handle deadlocks gracefully using TRY...CATCH.
  • Key Components :
    • ROLLBACK TRANSACTION: Ensures that the transaction is rolled back in case of a deadlock.
    • ERROR_MESSAGE(): Captures the deadlock error message.
  • Why Handle Deadlocks? :
    • Deadlocks can cause transactions to fail, so handling them improves system robustness.
    • Logging deadlocks helps identify and resolve contention issues.
  • Real-World Application :
    • In financial systems, deadlock handling ensures consistent account updates.

Additional Notes:

  • Use SET DEADLOCK_PRIORITY to control which transaction is chosen as the deadlock victim.
  • Analyze deadlock graphs to understand the root cause.
  • Important Considerations:
    • Avoid long-running transactions to reduce deadlock likelihood.

For more Practice: Solve these Related Problems:

  • Write a SQL query to simulate a deadlock scenario between two transactions and handle it using TRY...CATCH.
  • Write a SQL query to prioritize a specific transaction as the deadlock victim using SET DEADLOCK_PRIORITY.
  • Write a SQL query to log deadlock details, including the resources involved and the affected queries.
  • Write a SQL query to analyze deadlock graphs and identify the root cause of contention.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Identifying Bottlenecks with Query Profiling.
Next SQL Exercise: Debugging Recursive Queries.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.