w3resource

Optimize Workload by Skipping Locked Rows


Use SKIP LOCKED to Process Available Rows

Write a PostgreSQL query to lock rows using SELECT FOR UPDATE with the SKIP LOCKED option to process only unlocked rows.

Solution:

-- Lock available rows in the Orders table, skipping those already locked.
SELECT * FROM Orders -- Specify the table to query.
FOR UPDATE SKIP LOCKED; -- Skip rows that are currently locked.

Explanation:

  • Purpose of the Query:
    • The goal is to avoid waiting for locks by skipping rows that are currently locked by other transactions.
    • This demonstrates how SKIP LOCKED can improve throughput in concurrent processing.
  • Key Components:
    • FOR UPDATE SKIP LOCKED : Locks rows while skipping those that are already locked.
    • The query operates on the Orders table to fetch available rows.
  • Real-World Application:
    • Often used in job queues or order processing systems to allow multiple workers to process rows without conflict.

Notes:

  • Rows skipped due to being locked will not be processed by this query.
  • Use SKIP LOCKED when it’s acceptable to process only a subset of rows.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query to select and lock available rows from the Tasks table using FOR UPDATE SKIP LOCKED.
  • Write a PostgreSQL query to fetch pending orders from the Orders table using FOR UPDATE SKIP LOCKED to process only unlocked orders.
  • Write a PostgreSQL query to lock rows in the Jobs table using FOR UPDATE SKIP LOCKED where status = 'queued'.
  • Write a PostgreSQL query to select records from the Messages table using FOR UPDATE SKIP LOCKED to avoid waiting for locked rows.


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

Previous PostgreSQL Exercise: Use NOWAIT to Avoid Lock Waits.
Next PostgreSQL Exercise: Simulate a Deadlock Scenario.

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.