I would like to make Postgres choose the first next available id so that no error occurs in the following case:
CREATE TABLE test(
id serial PRIMARY KEY,
name varchar
);
Then:
INSERT INTO test VALUES (2,'dd');
INSERT INTO test (name) VALUES ('aa');
INSERT INTO test (name) VALUES ('bb');
This will give a constraint error since id
is primary.
How can I tell Postgres to insert the record with the next free id?
Generally it's best to never overrule the default in a
serial
column. If you sometimes need to provide id values manually, replace the standardDEFAULT
clausenextval('sequence_name')
of theserial
column with a custom function that omits existing values.Based on this dummy table:
Function:
Alter default:
It's not strictly a
serial
any more, butserial
is only a convenience feature anyway:And if you build this on top of a
serial
column theSEQUENCE
is automatically "owned" by the table column, which is probably a good thing.This is a slightly faster variant of:
Table and sequence name are hard coded here. You could easily parametrize the sequence name (like in the linked answer) and even the table name - and test existence with a dynamic statement using
EXECUTE
. Would give you a generic function, but the call would be a bit more expensive.SQL Fiddle.