I have two tables:
CREATE TABLE "user" ( username character varying(35) NOT NULL, CONSTRAINT user_pk PRIMARY KEY (username) ) CREATE TABLE item ( id serial NOT NULL, username character varying(35), user_item_number integer, item_value character varying(35), CONSTRAINT item_pk PRIMARY KEY (id), CONSTRAINT item_fk FOREIGN KEY (username) REFERENCES "user" (username) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT unique_item_username UNIQUE (username, user_item_number) )

I would like to auto-increment user_item_number separately for each username . The following figure shows an example. For each username : ( user1 , user2 ) user_item_number , form 1 starts and increases by 1. 
I assume that I should use some trigger before insertion, which get the maximum user_item_number for username that is inserted and increment it. But I do not know how to write this trigger.
I also do not know how to consider access to the convention (concurency insert is larger than a few lines with the same username value). I donβt want to get a constraint violation error when two lines with the same username and user_item_number , I would like the trigger to catch this error and the other to increase the value of user_item_number .
Any idea?
source share