I have a table with a primary key set on an id field that uses a sequence to generate numbers as its default value. When inserting records, this works fine and the sequence is correctly updated. However, if I insert records with an id field (e.g. an import from a backup), the sequence is not updated.
CREATE TABLE public.my_table (
my_id integer NOT NULL DEFAULT NEXTVAL('my_id_seq'),
name text,
CONSTRAINT my_primary PRIMARY KEY (myid)
);
CREATE SEQUENCE public.my_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
This updates the sequence:
INSERT INTO my_table (name) VALUES ('Bart');
This doesn't:
INSERT INTO my_table (my_id, name) VALUES (12, 'Bart');
Causing problems when the sequence hits 12 and I try to insert without an ID.
Is there a good/standard way to do this automatically? I know MySQL does it in its AUTO_INCREMENT
column (which is way I ran into this problem, I came from MySQL). I looked online and found some ways: using a trigger, or manually updating the sequence after inserting, but many of these resources are quite old. Perhaps version 9.1 has some features to address this?