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:
something1, 'something', 0
Update a row:
update mytable set whatever = something_new'something new', version = version + 1 where id = 1 and version = 0
If that row was not found, raisethrow 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.