Haki Benita Blog·
Why Row Locks Can Produce Surprising Join Results in PostgreSQL
Row Locks With Joins Can Produce Surprising Results in PostgreSQL
Key Takeaway
In PostgreSQL, an inner join waiting for a row lock can return no rows if another transaction updates the foreign key and commits, even though the foreign key constraint is enforced.
Why It Matters
At Read Committed, transactions that validate the current foreign-key relationship can lock the referencing row before looking up the related row, rather than relying on a join formed before the lock wait.
Technical Breakdown · Distilled from the original source
What the query reads before and after the lock wait
- The example runs at the default
Read Committedisolation level.car.owner_idis non-null and has an enforced foreign key.FOR NO KEY UPDATE OF carlocks only the car row. In the original plan,LockRowssits above theNested Loop, so the waiting session forms the old car–owner pair before it blocks on the car row. - After the other session changes
owner_idand commits,EvalPlanQualrechecks the join with the updated car row but does not look up the new owner. The inner join discards the mismatch; the left join retains the updated car row and fills the owner columns withNULL. Neither result implies that the new owner is missing or that the foreign key failed.
Lock the car before looking up its owner
- Put
SELECT * FROM car WHERE id = 1 FOR NO KEY UPDATEin a CTE or derived table and join toownerin the outer query. In the example plans,LockRowsmoves to the car side of the join. Once the wait ends, the outer join operation uses the updatedowner_idto find the existing new owner. - Rapid repeated button clicks triggered the production incident in a workflow not normally expected to be highly concurrent. The team looked for other affected sites and patched each by splitting the lookup into separate statements, locking and reading the car before querying its owner.
Source: Haki Benita Blog· hakibenita.com
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.