My objective is to get a primary key field automatically inserted when inserting new row in the table.
How to get a sequence going from session to session in Postg
This may be simpler than you think ...
My objective is to get a primary key field automatically inserted when inserting new row in the table.
Just set the default value of the column:
ALTER TABLE tbl ALTER COLUMN tbl_id SET DEFAULT nextval('my_seq'::regclass);
Or simpler yet, create the table with a serial type for primary key to begin with:
CREATE TABLE tbl(
tbl_id serial PRIMARY KEY
,col1 txt
-- more columns
);
It creates a dedicated sequence and sets the default for tbl_id automatically.
This way tbl_id is assigned the next value from the attached sequence automatically if you don't mention it in the INSERT. Works with any session, concurrent or not.
INSERT INTO tbl(col1) VALUES ('foo');
If you want the new tbl_id back to do something with it:
INSERT INTO tbl(col1) VALUES ('foo') RETURNING tbl_id;