0

I want to copy a CSV file into the table r. In the file, the string "NULL" represents NULL, so I tried:

copy r from 'file.csv' WITH NULL AS 'NULL' DELIMITER ';' CSV HEADER;

This works. But another file contains two values that represent NULL: The string "NULL" and an empty string "". How can I declare that several values should be interpreted as NULL?

3
  • technically "" isn't null its a blank string most of the time they are thought of the same but they can have different meanings. You could always just run an update statement after importing to change the several values to NULL. Commented Sep 27, 2016 at 16:34
  • I am not sure how to do that, as the column is a timestamp and it only allows timestamps and NULL. Commented Sep 27, 2016 at 16:37
  • yeah you would have to import as VARCHAR then convert to timestamp after handling the invalid values. Sorry I don't know postgressql's import method so I will let one of that platforms experts answer. cheers Commented Sep 27, 2016 at 16:39

1 Answer 1

1

As @Matt alluded, the best option here is to import the column as text and then convert it to timestamptz. So create the table like this:

CREATE TABLE r (
    ...
    t timestamp with time zone,
    ...
);

Then import the data using COPY as you suggested. Finally convert the timestamps like this:

ALTER TABLE r
ALTER COLUMN t
TYPE timestamptz
USING
    CASE t
        WHEN 'NULL' THEN NULL
        WHEN '' THEN NULL
        ELSE t::timestamptz
    END;
Sign up to request clarification or add additional context in comments.

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.