Sub topic 2
Server-side COPY versus psql \copy
This chapter assumes you know basic SQL, can connect to a database with psql, and understand what a CSV file is. The examples use a products table.
COPY has two forms that look almost identical. The difference is where the file lives. Server-side COPY reads or writes a file on the database server's filesystem. The psql meta-command \copy reads or writes a file on your own machine. psql sends the data over the connection, so the server never needs direct access to your files.
Server-side COPY
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);The server process interprets the path, so the file must exist on the server host. Reading or writing server files requires superuser rights or membership in the pg_read_server_files or pg_write_server_files role. Grant those roles only when needed.
psql \copy
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)Here the path refers to the machine running psql. \copy is a psql command, so it takes no trailing semicolon and must fit on one line.
Exporting with COPY TO
You can export a whole table or the result of a query:
\copy (SELECT id, name, price FROM products WHERE price > 10 ORDER BY id) TO 'expensive.csv' WITH (FORMAT csv, HEADER true)NULLs, empty strings, and quoting
In CSV format, an unquoted empty field loads as NULL. A quoted empty field ("") loads as an empty string. On export, NULL is written as an unquoted empty field, and an empty string is written as "". Keep these two cases distinct, or data changes silently on a round trip.
If your file uses a different marker for missing values, set it with the NULL option:
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true, NULL 'NULL')Fields that contain the delimiter, the quote character, or a newline must be quoted. The default quote character is the double quote. Change it with the QUOTE option only if your file requires it.
Exercise
Your CSV file writes missing prices as the text NULL. Which option makes COPY load those values as database NULLs?
Show answer
Add NULL 'NULL' to the WITH list, for example WITH (FORMAT csv, HEADER true, NULL 'NULL').