Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For instance:

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

How do you insert into table in this case?

like image 753
Charagh Jethnani Avatar asked Sep 09 '12 05:09

Charagh Jethnani


People also ask

Can you insert into an identity column?

By default, it's not possible to manually insert a value directly into an identity column value, but identity values can be manually entered if you turn on a session option.

Is it possible to only insert data in specific columns?

It is also possible to only insert data in specific columns.

How do you insert a single column?

To insert a single column: Right-click the whole column to the right of where you want to add the new column, and then select Insert Columns. To insert multiple columns: Select the same number of columns to the right of where you want to add new ones. Right-click the selection, and then select Insert Columns.

How do I add an identity column in PostgreSQL?

In PostgreSQL, the GENERATED AS IDENTITY constraint is used to create a PostgreSQL identity column. It allows users to automatically assign a unique value to a column. The GENERATED AS IDENTITY constraint is the SQL standard-conforming variant of the PostgreSQL's SERIAL column.


2 Answers

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

like image 138
Akash KC Avatar answered Oct 01 '22 00:10

Akash KC


insert into Participant values (default);
like image 32
chifung7 Avatar answered Oct 01 '22 02:10

chifung7