Domanda

I would like to import data into my postgresql table. I have .csv file that is formated like this:

1; John Blake
2; Roberto Young
3;Mark Palmer

Any solution how to strip first whitespace where it exists?

i used following code

\copy users from 'users.csv' using delimiters E';'

And it does keep whitespaces

È stato utile?

Soluzione

COPY to a temporary staging table and INSERT into the target table from there, trimming the text column.

CREATE TEMP TABLE tmp_x AS
SELECT * FROM users LIMIT 0;   -- empty temp table with structure of target

\copy tmp_x FROM '/absolute/path/to/file' delimiters E';'; -- psql command (!)

INSERT INTO users
      (usr_id,       usr,  ...) -- list columns
SELECT usr_id, ltrim(usr), ...
FROM   tmp_x;

DROP TABLE tmp_x;  -- optional; is destroyed at end of session automatically

ltrim() only trims space from the left of the string.

This sequence of actions performs better than updating rows in the table after COPY, which take longer and produce a dead rows. Also, only newly imported rows are manipulated this way.

Related answer:
Delete rows of a table specified in a text file in Postgres

Altri suggerimenti

You won't be able to use COPY alone to do that.

You can use an UPDATE coupled with trim:

UPDATE table SET column = trim(from column)

Or use a script to clean the data before bulk inserting the data to the DB.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top