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 PostgreSQL?
doubleemploi@hanbei:/home/yves$ psql -d test
Mot de passe :
psql (8.4.13)
Saisissez « help » pour l''aide.
test=> create sequence test001 start 10;
CREATE SEQUENCE
test=> select currval('test001');
ERREUR: la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session
--- current value not yet defined this session (???)
test=> select setval('test001', 10);
setval
--------
10
(1 ligne)
test=> select currval('test00');
currval
---------
10
(1 ligne)
test=> \q
test@hanbei:/home/yves$ psql -d test
Mot de passe :
psql (8.4.13)
Saisissez « help » pour l''aide.
test=> select currval('test001');
ERREUR: la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session
This may be simpler than you think …
Just set the default value of the column:
Or simpler yet, create the table with a
serialtype for primary key to begin with:It creates a dedicated sequence and sets the default for
tbl_idautomatically.In Postgres 10 or later, consider an
IDENTITYcolumn instead. See:This way
tbl_idis assigned the next value from the attached sequence automatically if you don’t mention it in theINSERT. Works with any session, concurrent or not.If you want the new
tbl_idback to do something with it: