My table is defined as:
CREATE TABLE accounts IF NOT EXISTS (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
At some circumstances, I want to fetch next val of id before inserting data into a table at PostgreSQL. So, I created a sequence for that:
CREATE SEQUENCE IF NOT EXISTS accounts_sequence
I can fetch the next val from sequence and then use it at insert. However, it needs to be auto incremented by same sequence if I insert a row without providing the id.
How can I create a PostgreSQL table id field and define a custom sequence for it?
A
serialcolumn will automatically create a sequence in the background.If you want to manually call
nextval()you can usepg_get_serial_sequence()to obtain the sequence name:Note that the use of
serialis discouraged in modern Postgres versions in favor ofidentitycolumns.