Optimistic locking is typically implemented with…
Options
SELECT ... FOR UPDATEon the row you want to change- A version column, updated only when
versionstill matches (Correct option) - Table locks taken at the start of every transaction
- 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.