Home > database >  Import CSV file via PSQL With Array Values
Import CSV file via PSQL With Array Values

Time:08-08

I have a very simple table where I would like to insert data from a CSV into it.

create table products(
  id integer primary key,
  images text[]
);

Here is what I am currently trying with my csv:

1,"['hello.jpg', 'world.jpg']"
2,"['hola.jpg', 'mundo.jpg']"

When I do the following, I get a syntax error from psql, with no additional information what could have gone wrong.

\copy products 'C:\Users\z\Downloads\MOCK_DATA.csv' WITH DELIMITER ',';

Does anyone know how to format my array values properly?

CodePudding user response:

You can add headers to your CSV and use CSV to SQL converters like this and copy it to TEMPORARY TABLE and if the data does not need to be sanitized, then you are good to go. In case you are not using pgAdmin, please, it makes things way handier.

CodePudding user response:

If you remove the square brackets from the csv file then I would have the table like this (images as text rather than text[]):

create table products_raw
(
  id integer primary key,
  images text
);

plus this view

create view products as 
  select id, ('{'||images||'}')::text[] as images 
  from products_raw;

and use the view henceforth. Anyway I would rather have the CSV file like this, no formatting, just data:

1,"hello.jpg,world.jpg"
2,"hola.jpg,mundo.jpg"

It is also worth considering to attach the csv file as a foreign table using file_fdw. It is a bit more complicated but usually pays off with several benefits.

  • Related