Consider the following transaction:
BEGIN;
SELECT *
FROM A
JOIN B ON A.id = B.a_id
WHERE A.id = 123
ORDER BY A.id, B.id
FOR UPDATE;
-- more ops...
COMMIT;
I'm using the ORDER BY clause just to ensure that rows are locked in a consistent way so that, if multiple concurrent connections execute the same transaction, a deadlock would not happen.
My questions are:
- Am I using the
ORDER BYclause in the right way (considering I'm doing aJOIN)? - In what exact order are the rows locked? I'm triyng to lock all rows from table A before (in order by id) and then all rows from table B (again in order by id) but I guess this is not the right way to go.
I asked a similar question months ago, but JOIN clause was not used.
The rows will be locked in the order that they are emitted by the
ORDER BY. One consequence of that is that it will lock rows from both tables – one result row of the join will consist of a row from each of the tables.Note that if the
idcolumns receive concurrent updates, the result may have an ordering different from the one specified inORDER BY, so rows could get locked in a different order than you intend. But then, primary keys should not get modified anyway.Assuming that
idis never updated, and you want to lock the rows inafirst, you could use a temporary table: