Skip to main content
3 of 3
added 307 characters in body
Neil McGuigan
  • 8.6k
  • 5
  • 40
  • 56

What you are looking for is called Optimistic Concurrency Control.

Add an int column to your table called version. Start at 0.

create table mytable (
  id bigserial primary key,
  whatever text,
  version int not null default 0
);

Add a row:

insert into mytable (whatever) values ('something');

Read a row:

select id, whatever, version from mytable where id=1

Results:

1, 'something', 0

Update a row:

update mytable set whatever = 'something new', version = version + 1 where id = 1 and version = 0

If that row was not found, throw an exception. If you have a REST API on top of your database, you should use HTTP 409 Conflict.

If you use an ORM like Hibernate, you can just add a field with a @Version annotation and it will handle this for you.

Neil McGuigan
  • 8.6k
  • 5
  • 40
  • 56