37

I have csv file (y.csv) in the folowing format:

 's', '1999-10-10', '1999-12-12'
 'b', '99-10-10 BC', '1-10-10 BC'
 'c', 'NULL', 'NULL'

I have a few NULL values (for date) in it which I have indicated through the string 'NULL'.

I am trying to copy the csv file into postgres. For doing so I have created a table:

create table r (id character varying(255), timebegin date, timeend date);

Now I am trying to copy the above .csv file into postgres using the command

copy r from '/home/y.csv' delimiter ',' csv;
ERROR:  invalid input syntax for type date: " 'NULL'"
CONTEXT:  COPY r, line 1, column timebegin: " 'NULL'"

On doing so I am getting an error with NULL. Can someone please help me figure out the error and correct it.

4 Answers 4

62

Have you tried it?

 copy r from '/home/y.csv' delimiter ',' csv WITH NULL AS 'null';
Sign up to request clarification or add additional context in comments.

6 Comments

I try but I receive this error: ERROR: syntax error at or near "WITH NULL";
copy r from '/home/y.csv' with delimiter as ',' NULL AS 'null' csv; I don't know if syntax changed in later version of pgsql, but that's what worked for me.
@monteirobrena, leave off the 'WITH'. It will work without it.
I usually go with copy table from filename WITH (FORMAT CSV, NULL "NULL") and it works
For me, the syntax that I use, working on PG 9.3 and above, is copy r from '/home/y.csv' WITH (delimiter ',', FORMAT csv, NULL 'null)';
|
10

after giving the path of the file, we need to use 'With' before adding other paramters -

copy r from '/home/y.csv' with delimiter ','  NULL AS 'null' csv header;

Comments

3

The error is because you are inserting NULL as string. Remove the quotes around NULL and it should work.

2 Comments

This is not a solution. What if this was an automated process?
@FreshPrinceOfSO : I know this may not be an ideal solution but as it was mentioned in the question as I have a few NULL values (for date) in it which I have indicated through the string 'NULL'. It is clear that the error was because of trying to insert a string in the date column.
1

1st Replace all NULL with ' ' (Space).

Then COPY r FROM '/home/y.csv' WITH DELIMITER ',' NULL as ' ' CSV;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.