Browse topics

Import and export CSV with COPY

Version
19
Review
Draft

Summary#

COPY FROM loads rows in bulk. COPY TO exports a table or query. In psql, \copy reads or writes files on the client machine using the privileges of the account running psql.

Syntax#

sql
COPY table_name (column_list) FROM STDIN WITH (FORMAT csv, HEADER MATCH);
COPY (query) TO STDOUT WITH (FORMAT csv, HEADER);

-- In psql, read a local file.
\copy table_name (column_list) FROM 'input.csv' WITH (FORMAT csv, HEADER MATCH)

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE stations (
    station_id integer PRIMARY KEY,
    label      text NOT NULL,
    note       text
);

COPY stations (station_id, label, note)
FROM STDIN WITH (FORMAT csv, HEADER MATCH);
station_id,label,note
1,"East, upper",
2,West,""
3,South,covered
\.

SELECT station_id, note IS NULL AS note_is_null, length(note) AS note_length
FROM stations
ORDER BY station_id;

COPY (SELECT station_id, label, note FROM stations ORDER BY station_id)
TO STDOUT WITH (FORMAT csv, HEADER);

ROLLBACK;

Expected output#

Text
station_id|note_is_null|note_length
1|t|NULL
2|f|0
3|f|7
(3 rows)
station_id,label,note
1,"East, upper",
2,West,""
3,South,covered

Common mistakes#

A file named in SQL COPY lives on the database server. For a local file, use \copy. In default CSV format, an unquoted empty field loads as SQL null, while "" loads as an empty string. HEADER MATCH checks the input column names and their order. End inline input in a psql script with \. on its own line.

Version applicability#

The example uses HEADER MATCH, added in PostgreSQL 15. For earlier releases with CSV support, use HEADER to skip the header and verify the column order separately.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0