Search code examples
postgresqlcsvpsql

psql import csv and generate uuid


I'm trying to import from CSV to Postgres and generate a uuid, uuid_generate_v4(), during the import to populate a table.

Postgres version: 14

Postgres Table

  • Country
    • id (primary key)
    • country_name
    • country_ISO_Code

Psql import

\copy "Country" (select uuid_generate_v4() as "id", "country_name", "country_ISO_code") FROM 'C:\Users\.......\data.csv' (format csv, header, delimiter ',')

However, that throws an error \copy: parse error at "as"

How do I properly instruct psql to use uuid_generate_v4() as id column?


Solution

  • You can't copy "from" a select statement. You need to define a default value for your primary key:

    create table country
    (
      id uuid primary key default gen_random_uuid(),
      country_name text not null,
      country_iso_code text not null
    );
    

    Then tell the \copy command that your input file only contains two columns:

    \copy country (country_name, country_iso_code) from 'data.csv' (format csv, header, delimiter ',')