CodeBlanks Logo Icon CodeBlanks

What is a lock?

Queue concurrent access.

What is a lock?

A lock controls concurrent access. Two operations cannot write the same resource simultaneously.

SELECT * FROM accounts WHERE id = 1 FOR UPDATE;

This query locks the row.

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

What is a lock? — details

Locks ensure data consistency. But excessive locking reduces performance.

For example, when two people buy the last item at the same moment, a lock prevents the stock from being decreased twice.

Practice What is a lock?

Lock the id=1 row in accounts with FOR UPDATE.

Starter code

query.sql
-- lock row
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 does a lock control?

  • An index
  • Query speed
  • Concurrent access Correct answer
  • A view

Explanation: A lock controls concurrent access.

2 Add FOR UPDATE

Question
SELECT * FROM accounts WHERE id = 1 ____
Answer
SELECT * FROM accounts WHERE id = 1 FOR UPDATE

Explanation: FOR UPDATE is the right answer.

3 What is a lock: match the terms

Term Meaning
lock lock
concurrent parallel
FOR UPDATE row lock
consistent safe

All lessons in Advanced