Skip to content
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 Committed isolation level. car.owner_id is non-null and has an enforced foreign key. FOR NO KEY UPDATE OF car locks only the car row. In the original plan, LockRows sits above the Nested Loop, so the waiting session forms the old car–owner pair before it blocks on the car row.
  • After the other session changes owner_id and commits, EvalPlanQual rechecks 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 with NULL. 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 UPDATE in a CTE or derived table and join to owner in the outer query. In the example plans, LockRows moves to the car side of the join. Once the wait ends, the outer join operation uses the updated owner_id to 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.

Read Official Source

Related PostgreSQL Reference