0

I would need to perform this kind of logic in a serializable way:

account table has columns: 'accountName', 'location', 'worth', ...
Assume no unique key exists.

Some accounts are logically (according to an application) in a same group.

Example:

accountNameOne - group1 accountNameTwo - group1

accountNewOne - group2 accountNewTwo - group2

There are many clients application trying to insert one account member of their group concurrenlty. I want to have the guarantee to insert only one account per group.

BEGIN;

select *
from account 
where accountName in (list of account names inside a group)

-- if result is not empty exit there's already an account of the group
-- otherwise we want to insert it

INSERT INTO account (accountName, column2, column3, ...)
VALUES ('accountInAGroup', value2, value3, ...);

COMMIT;

As far as I know Repeatable reads isolation level cannot help in this, I am basically left with using SERIALIAZABLE I guess.

Can you help me understand if my reasoning here is correct ? Is Repeatable reads really not enough for this ?

4
  • The question is a bit unclear, but it looks like INSERT ... ON CONFLICT is the answer. Commented Feb 14 at 16:37
  • Hey Laurenz, yes sorry, maybe because I mentioned a unique costraint, I don't have an easy way to put in place one, I was looking at pg_advisory_xact_lock, what do you think ?
    – GionJh
    Commented Feb 14 at 17:05
  • An advisory lock cannot be the solution. I suggest that you edit the question and make your SQL sample syntactically correct. Commented Feb 14 at 17:08
  • Done, thanks for your help :)
    – GionJh
    Commented Feb 14 at 17:28

1 Answer 1

1

Yes, the SERIALIZABLE isolation level is the only way for the database to guarantee that no anomalies can occur.

Serializing the execution of the function using advisory locks would only help if that function is the only place where data are inserted into this table.

1
  • Thanks a lot Laurennz!
    – GionJh
    Commented Feb 14 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.