In PostgreSQL how do you insert into a table with only one identity column?

Charagh Jethnani picture Charagh Jethnani · Sep 9, 2012 · Viewed 20k times · Source

For instance:

{create table Participant ( id serial, primary key(id) );}

How do you insert into table in this case?

Answer

Akash KC picture Akash KC · Sep 9, 2012

If you create the table like above,

You can use default in following way to insert:

INSERT INTO Participant values(default); 

Check out SQLFIDDLE.

Another way to insert is:

INSERT INTO Participant values(NEXTVAL('Participant_id_seq')); 

CREATE TABLE will create implicit sequence "Participant_id_seq" for serial column "Participant.id".

You can get the sequence for the table using pg_get_serial_sequence function in following way:

pg_get_serial_sequence('Participant', 'id')

It will take new value from sequence using NEXTVAL().

Check out SQLFIDDLE