Repaso
Español
Databases & SQLAdvancedDB-13

Optimistic locking is typically implemented with…

Options

  1. SELECT ... FOR UPDATE on the row you want to change
  2. A version column, updated only when version still matches (Correct option)
  3. Table locks taken at the start of every transaction
  4. A cron job that checks for conflicts every minute

Answer

A version column: UPDATE ... SET version = version + 1 WHERE id = ? AND version = ? and checking affected rows

Why

Optimistic locking assumes conflicts are rare and does not lock anything while you read.

Each row has a version number. When saving, you update only if the version is still the one you read, and increase it.

If 0 rows were updated, someone else saved first: reload and retry, or show a conflict message.

Pessimistic locking (SELECT ... FOR UPDATE) locks the row up front instead.

Remember

Optimistic = check a version number when saving.

Key terms

Practice this question in Repaso