CodeBlanks Logo Icon CodeBlanks

Summary - Locking

Update a balance safely with SELECT FOR UPDATE.

Summary - Locking

A lock controls concurrent access. FOR UPDATE locks a row; deadlock is mutual waiting.

SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

Summary locking query.

All columns are selected from accounts. WHERE keeps only the rows where id = 1 FOR UPDATE holds.

Practice Summary - Locking

Summary: lock the id=1 row in accounts with FOR UPDATE.

Starter code

query.sql
-- summary locking
SELECT * FROM accounts WHERE id = 1

Sample solution

query.sql
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

Expected output

id  balance
1   500

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What locks a row?

  • FOR READ
  • FOR LOCK
  • FOR SHARE
  • FOR UPDATE Correct answer

Explanation: FOR UPDATE locks a row.

2 Summary - Locking: match the terms

Term Meaning
shared read
exclusive write
FOR UPDATE row lock
deadlock deadlock

All lessons in Advanced