简体   繁体   中英

psql copy from csv automatically generating ids

Well consider a table created like this:

CREATE TABLE public.test
(
    id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
    name text,
    PRIMARY KEY (id)
)

So the table has a unique 'id' column that auto generates default values using a sequence.

Now I wish to import data from a csv file, extending this table. However "obviously" the ids need to be unique, and thus I wish to let the database itself generate the ids, the csv file itself (coming from a complete different source) has hence an "empty column" for the ids:

,username
,username2

However if I then import this csv using psql:

\copy public."user" FROM '/home/paul/Downloads/test.csv' WITH (FORMAT csv);

The following error pops up:

ERROR:  null value in column "id" violates not-null constraint

So how can I do this?

The empty colum from the CSV file is interpreted as SQL NULL, and inserting that value overrides the DEFAULT and leads to the error.

You should omit the empty column from the file and use:

\copy public."user"(name) FROM '...' (FORMAT 'csv')

Then the default value will be used for id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM