w3resource

Prevent Delays by Using NOWAIT in Row Locking


Use NOWAIT to Avoid Lock Waits

Write a PostgreSQL query to lock a row using SELECT FOR UPDATE with the NOWAIT option to avoid waiting if the row is already locked.

Solution:

-- Attempt to lock the employee row with ID 101 without waiting.
SELECT * FROM Employees -- Specify the table to query.
WHERE employee_id = 101
FOR UPDATE NOWAIT; -- Do not wait if the row is locked.

Explanation:

  • Purpose of the Query:
    • The goal is to immediately return an error instead of waiting for the lock if the row is already held by another transaction.
    • This demonstrates how NOWAIT can be used to prevent long lock wait times.
  • Key Components:
    • FOR UPDATE NOWAIT : Combines row locking with a non-waiting mechanism.
    • WHERE employee_id = 101 : Identifies the specific row for locking.
  • Real-World Application:
    • Useful in high-concurrency environments where waiting for locks is not acceptable and prompt error handling is needed.

Notes:

  • If the row is locked, the query will raise an error immediately.
  • Applications must handle the error gracefully, possibly by retrying later.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query to lock a specific row in the Sessions table using SELECT FOR UPDATE NOWAIT where session_id = 300.
  • Write a PostgreSQL query to lock a record in the Orders table using NOWAIT to immediately raise an error if the row is locked, filtering by order_id = 789.
  • Write a PostgreSQL query to attempt locking a customer record in the Customers table with NOWAIT, where customer_id = 150.
  • Write a PostgreSQL query to lock a row in the Products table using SELECT FOR UPDATE NOWAIT when product_id = 250.


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

Previous PostgreSQL Exercise: Lock an Entire Table Using LOCK TABLE.
Next PostgreSQL Exercise: Use SKIP LOCKED to Process Available Rows.

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.