Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSTGRESQL :INSERT INTO ... SELECT with auto generated column

I have two tables A(id, col1, col2) and B(col3, col4, col5, col6)

the column "id" in table A is an auto generated, not null, primary key.

To insert data from table B to table A, I am trying

INSERT INTO A(col1, col2)
(SELECT col3, col4 from B)

This statement throws error

ERROR:  null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, "abc", "def")

I also tried

INSERT INTO A(id, col1, col2)
(SELECT DEFAULT, col3, col4 from B)

this throws error

ERROR:  syntax error at or near "DEFAULT"

Why is postgres not auto generating value for column "id" ? The query works if I provide "id" from table B, or if I insert single row (without select) and providing "DEFAULT" keyword for auto generated column.

EDIT: Table creation query

CREATE TABLE A 
(
id bigint NOT NULL, 
col1 character varying(10), 
col2 character varying(10), 
CONSTRAINT A_pk PRIMARY KEY (id) 
); 
ALTER TABLE A OWNER TO user1; 

CREATE SEQUENCE A_id_seq 
START WITH 1 
INCREMENT BY 1 
NO MINVALUE 
NO MAXVALUE 
CACHE 1; 

ALTER TABLE A_id_seq OWNER TO user1; 

ALTER SEQUENCE A_id_seq OWNED BY A.id; 
like image 256
Somil Bhandari Avatar asked Apr 09 '16 19:04

Somil Bhandari


People also ask

Is there auto increment in PostgreSQL?

By simply setting our id column as SERIAL with PRIMARY KEY attached, Postgres will handle all the complicated behind-the-scenes work and automatically increment our id column with a unique, primary key value for every INSERT .

What is Upsert in PostgreSQL?

In PostgreSQL, the UPSERT operation means either UPDATE or INSERT operation. The UPSERT operation allows us to either insert a row or skip the insert operation if a row already exists and update that row instead. Suppose you want to insert bulk data from one table to another table that already has some data.

What is select insert?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

What is needed for an insert on conflict update to work?

You must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required. If a column list is specified, you only need INSERT privilege on the listed columns.


1 Answers

Don't use an explicit sequence. Just define the column as serial or bigserial:

CREATE TABLE A (
    id bigserial NOT NULL, 
    col1 character varying(10), 
    col2 character varying(10), 
    CONSTRAINT A_pk PRIMARY KEY (id) 
); 

Then the insert will be fine. Here is a SQL Fiddle.

like image 152
Gordon Linoff Avatar answered Nov 15 '22 04:11

Gordon Linoff