Inserting a record into a table with a column declared with the SERIAL function

DatabasePostgresql

Database Problem Overview


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)
);

Database Solutions


Solution 1 - Database

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');

Solution 2 - Database

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)

Solution 3 - Database

These query work for me:

insert into <table_name> (all columns without id serial)
select (all columns without id serial)
 FROM <source> Where <anything>;

Solution 4 - Database

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...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAntiGMOView Question on Stackoverflow
Solution 1 - DatabaseCraig RingerView Answer on Stackoverflow
Solution 2 - DatabasefrancsView Answer on Stackoverflow
Solution 3 - DatabaseHiram WalkerView Answer on Stackoverflow
Solution 4 - DatabaseChetPricklesView Answer on Stackoverflow