Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new row with all default values in Postgres?

Tags:

sql

postgresql

I have a table with two columns, id and created. Both have default values, so I should be able to insert a new row without supplying any data.

However, this syntax does not work:

INSERT INTO books () VALUES () 

I would also like to return the generated id of the inserted row. This syntax also does not work:

INSERT INTO books () VALUES () RETURNING id 

How do I write this query in Postgres SQL?

like image 293
sdgfsdh Avatar asked Nov 28 '17 14:11

sdgfsdh


People also ask

What is default constraint in PostgreSQL?

In PostgreSQL, the default constraint types are p , f , u , and c . The PRIMARY KEY is named by default with the table name, an underscore (' _ '), and ' pkey '.

How do I add a default value?

Set a default valueClick the All tab in the property sheet, locate the Default Value property, and then enter your default value.

How do I add multiple values in PostgreSQL?

PostgreSQL INSERT Multiple Rows First, specify the name of the table that you want to insert data after the INSERT INTO keywords. Second, list the required columns or all columns of the table in parentheses that follow the table name. Third, supply a comma-separated list of rows after the VALUES keyword.


2 Answers

According to INSERT syntax:

insert into books default values
returning id;
like image 169
klin Avatar answered Sep 23 '22 19:09

klin


here is example (basically, just use DEFAULT):

t=# create table d(i int default 0, t text default 'a');
CREATE TABLE
t=# insert into d values(DEFAULT,DEFAULT) returning *;
 i | t
---+---
 0 | a
(1 row)

INSERT 0 1
like image 24
Vao Tsun Avatar answered Sep 22 '22 19:09

Vao Tsun