63

My database is using PostgreSQL. One table is using the serial auto-increment macro. If I want to insert a record into the table, do I still need to specify that value, or it is be automatically assigned for me?

CREATE TABLE dataset
(
    id serial NOT NULL,
    age integer NOT NULL,
    name character varying(32) NOT NULL,
    description text NOT NULL DEFAULT ''::text
    CONSTRAINT dataset_pkey PRIMARY KEY (id)
);
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
AntiGMO
  • 1,535
  • 5
  • 23
  • 38

5 Answers5

116

Using the DEFAULT keyword or by omitting the column from the INSERT list:

INSERT INTO dataset (id, age, name, description)
VALUES (DEFAULT, 42, 'fred', 'desc');

INSERT INTO dataset (age, name, description)
VALUES (42, 'fred', 'desc');
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
6

If you create a table with a serial column then if you omit the serial column when you insert data into the table PostgreSQL will use the sequence automatically and will keep the order.

Example:

skytf=> create table test_2 (id serial,name varchar(32));
NOTICE:  CREATE TABLE will create implicit sequence "test_2_id_seq" for serial column "test_2.id"
CREATE TABLE

skytf=> insert into test_2 (name) values ('a');
INSERT 0 1
skytf=> insert into test_2 (name) values ('b');
INSERT 0 1
skytf=> insert into test_2 (name) values ('c');
INSERT 0 1

skytf=> select * From test_2;
 id | name 
----+------
  1 | a
  2 | b
  3 | c
(3 rows)
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
francs
  • 8,511
  • 7
  • 39
  • 43
5

These query work for me:

insert into <table_name> (all columns without id serial)
select (all columns without id serial)
 FROM <source> Where <anything>;
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Hiram Walker
  • 129
  • 2
  • 2
  • 4
    Is `all columns without id serial` a special keyword? – domids Jun 27 '19 at 13:20
  • 2
    @Snozzlebert no this was just the poster's shorthand. Basically means that in the column list you include any column that is not of type serial, and in the select list the same. – Sean Coley Jun 16 '20 at 16:04
2

Inserting multiple rows wasn't working for me in this scenario:

create table test (
  id bigint primary key default gen_id(),
  msg text not null
)

insert into test (msg)
select gs
from generate_series(1,10) gs;

because I had mistakenly marked my gen_id function IMMUTABLE.

The insert query was being optimized to only call that function once rather than 10 times. Oops...

ChetPrickles
  • 820
  • 13
  • 8
1

For example, you create "person" table with "id" of serial and "name" as shown below:

CREATE TABLE person (
  id serial PRIMARY KEY,
  name VARCHAR(50)
)

Then, you can use DEFAULT for "id" of serial and insert rows without column(field) names as shown below:

INSERT INTO person VALUES (DEFAULT, 'John'), (DEFAULT, 'Tom');
postgres=# SELECT * FROM person;
 id | name
----+------
  1 | John
  2 | Tom
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129