7

Lets say that there are multiple parallel transactions that all do the same query:

SELECT * FROM table1 FOR UPDATE;

Can this result in a deadlock?

To put it in another way. Is the operation "lock all rows" in the above statement atomic or are the locks acquired along the way while the the records are processed?

1 Answer 1

9

Yes, it can result in a deadlock.

This is pretty easy to demonstrate. Set up a test table:

CREATE TABLE t AS SELECT i FROM generate_series(1,1000000) s(i);

... and then run these two queries in parallel:

SELECT i FROM t ORDER BY i FOR UPDATE;
SELECT i FROM t ORDER BY i DESC FOR UPDATE;

You can prevent deadlocks by ensuring that all processes acquire their locks in the same order. Alternatively, if you want to lock every record in the table, you can do it atomically with a table lock:

LOCK t IN ROW SHARE MODE;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.