Is there a way to select rows in Postgresql that aren\'t locked? I have a multi-threaded app that will do:
Select... order by id desc limit 1 for update
My solution is to use the UPDATE statement with the RETURNING clause.
Users
-----------------------------------
ID | Name | flags
-----------------------------------
1 | bob | 0
2 | fred | 1
3 | tom | 0
4 | ed | 0
Instead of SELECT .. FOR UPDATE use
BEGIN;
UPDATE "Users"
SET ...
WHERE ...;
RETURNING ( column list );
COMMIT;
Because the UPDATE statement obtains a ROW EXCLUSIVE lock on the table its updating you get serialized updates. Reads are still allowed, but they only see data before the start of the UPDATE transaction.
Reference: Concurrency Control Chapter of Pg docs.