Search code examples
sqlpostgresqlprimary-keyauto-incrementsql-insert

Insert row into table with only a primary key field


Googling around told me to try this:

insert into Plan default values;

but I got:

null value in column "id" violates not-null constraint

or this:

insert into Plan (id) values (null);

but I got the same thing.

The examples were for SQL: is there something different for PostgreSQL?

Table structure:

  create table Plan (
    id int4 not null,
    primary key (id)
); 

Solution

  • You should create a sequence and set the default as nextval like so:

    create sequence plan_sequence
    start 100
    increment 1
    ;
    
      create table plan (
        id int4 not null default nextval('plan_sequence'),
        primary key (id)
    ); 
    

    A sequence provides an auto-incrementing value. It is used for primary keys, etc.