user1420752 user1420752 - 1 year ago 90
SQL Question

Why doesn't the PostgreSQL COPY command allow NULL values inside arrays?

I have the following table definition:

create table null_test (some_array character varying[]);

And the following SQL file containing data.

copy null_test from stdin;

When unnesting the data (with
select unnest(some_array) from null_test
), the second value is "N", when I am expecting NULL.

I have tried changing the data to look as follows (to use internal quotes on the array value):

copy null_test from stdin;

The same non-null value "N" is inserted?

Why is this not working and is there a workaround for this?


As per the accepted answer, the following worked. However, the two representation of NULL values within a COPY command depending on whether you're using single or array values is inconsistent.

copy null_test from stdin;

Answer Source

\N represents NULL as a whole value to COPY, not as part of another value and \N isn't anything special to PostgreSQL itself. Inside an array, the \N is just \N and COPY just passes the array literal to the database rather than trying to interpret it using COPY's rules.

You simply need to know how to build an array literal that contains a NULL and from the fine manual:

To set an element of an array constant to NULL, write NULL for the element value. (Any upper- or lower-case variant of NULL will do.) If you want an actual string value "NULL", you must put double quotes around it.

So you could use these:


to get NULLs in your arrays.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download