I defined an attribute in my table of type serial4
, so when I insert a new row, the attribute is automatically incremented:
myTable (id serial4, name varchar(25), whatever whatever, ...);
To insert a new entry, I just strip off the id
attribute in the association list:
insert into myTable (name, whatever, ...) values ('foo', ...);
Now, if my table has a large number of attributes, the association list is exhausting to write.
I just want to write:
insert into myTable values (...);
But if the first attribute of myTable
is the serial4 id
. What should I write in the VALUES
list to get the id
being incremented +1 from the last inserted value?
insert into myTable values (?, 'foo', ...);
The INSERT
command accepts the key word DEFAULT
:
INSERT INTO my_table VALUES (DEFAULT, 'foo', ...);
The serial
pseudo data type (synonym: serial4
) is just a notational convenience for an integer
column that retrieves its default values from an attached SEQUENCE
. By using the DEFAULT
key word, the next value from the sequence is inserted like any other default value.
Aside: it's typically not advisable to omit the target column list in persisted code. Any later change to the table will break that code it confusing ways.