Sub topic 2
Describing your file: the CSV format options
COPY needs to know how your file is laid out before it can read or write it. This chapter covers the options that describe that layout: FORMAT, HEADER, DELIMITER, QUOTE, ESCAPE and ENCODING. It also covers the FORCE_* options briefly. The next chapters use these options in real imports and exports.
I assume you can write basic SQL (CREATE TABLE, INSERT, SELECT), use psql, and recognize a CSV file. NULL handling gets its own chapter, so here it appears only where a format option affects it.
Where the options go
Options go in a parenthesized list after WITH. They are separated by commas and apply to COPY FROM and COPY TO alike, except where noted.
COPY products TO STDOUT
WITH (FORMAT csv, HEADER true, DELIMITER ',', QUOTE '"');Older documentation also shows a keyword style such as COPY products TO STDOUT CSV HEADER. It still works, but the parenthesized list is the current form and the only one that supports every option. This tutorial uses it throughout.
Choosing the format
FORMAT selects one of three formats:
| Format | What it is | Default delimiter |
|---|---|---|
| `text` | PostgreSQL's default format, with backslash escapes such as `\N` for NULL and `\t` for a tab | tab |
| `csv` | Comma-separated values with quoting rules | comma |
| `binary` | PostgreSQL-specific binary representation, not human-readable | not applicable |
If you omit FORMAT, you get text, not csv. This causes a common surprise: a CSV file loaded without FORMAT csv is read as tab-delimited, and the load fails with missing data for column "name" or similar. Several options in this chapter (QUOTE, ESCAPE, FORCE_QUOTE) are valid only with FORMAT csv.
How CSV mode reads a line
In CSV mode each line is a row, and the delimiter separates fields. A field wrapped in the quote character is read literally. Inside quotes, the delimiter and line breaks are ordinary data, so one quoted field can span several lines.
Unlike text format, CSV mode gives the backslash no special meaning by default. A backslash is an ordinary character unless you choose it as the ESCAPE character.
HEADER
HEADER tells COPY whether the file has a first line of column names.
- On
COPY FROM,HEADER trueskips the first line. The skipped names are discarded and are not matched to table columns. Mapping is by position, so a header does not reorder anything. - On
COPY TO,HEADER truewrites a first line with the column names. For a query, these are the output column names, so aliases likeprice AS costshow up in the header. - On PostgreSQL 15 and later,
COPY FROMalso acceptsHEADER MATCH. COPY then checks that the header names equal the column names, in order, and fails if they differ.
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER match);HEADER match is a cheap guard against a file whose columns were reordered by someone else. HEADER defaults to false. If your file has a header and you forget HEADER true, the header row is treated as data. The load then typically fails with an error like invalid input syntax for type integer: "id". That error is the usual sign of a missed header.
DELIMITER
DELIMITER sets the character that separates fields. It must be a single one-byte character, and it can't be a newline or carriage return. In CSV mode it also must differ from the quote character.
Typical choices are semicolon (common in spreadsheets exported in locales that use a decimal comma), pipe |, and tab. For a tab, use an escape string:
\copy products FROM 'products.tsv' WITH (FORMAT csv, HEADER true, DELIMITER E'\t')This reads a tab-separated file with CSV quoting rules, which differs from the text format. Spreadsheet-produced TSV files usually quote fields, so FORMAT csv with a tab delimiter is often the right reading.
A multi-character separator such as || is rejected with COPY delimiter must be a single one-byte character. Preprocess such a file, for example with sed, before loading it.
QUOTE and ESCAPE
QUOTE sets the character that wraps a field. The default is the double quote ". A field must be quoted when it contains the delimiter, the quote character, or a line break. Without quoting, a comma inside Gadget, large splits the field, and COPY fails with extra data after last expected column.
To put the quote character itself inside a quoted field, there are two conventions. ESCAPE selects which one COPY uses:
- Doubling: the default.
ESCAPEequalsQUOTE, so"Says ""hello"""is the valueSays "hello". - Backslash-style: set
ESCAPE '\'and the file writes"Says \"hello\"". The escape character precedes the quote character.
Both options must be a single one-byte character, and both apply only in CSV mode.
On output, COPY TO uses the same settings. It quotes a field only when it needs to, and it escapes embedded quotes using ESCAPE. When you export for a consumer that expects backslash escapes, set ESCAPE on the export, and set the same value when you read the file back.
A self-contained example
You can try these options without any file on disk. In a psql script, COPY ... FROM STDIN reads the lines that follow it, up to a line holding only \.. Save this as format_demo.sql and run it with psql -f format_demo.sql:
CREATE TEMP TABLE demo (
id integer,
name text,
note text
);
COPY demo FROM STDIN
WITH (FORMAT csv, HEADER true, DELIMITER ';', QUOTE '"');
id;name;note
1;Widget;"Says ""hello"""
2;"Gadget; large";"two
lines"
3;Plain;
\.
SELECT id, name, note FROM demo ORDER BY id;Three rows load:
- Row 1 has the value
Says "hello"innote, because the doubled quotes collapse to one. - Row 2 has the name
Gadget; large, because the semicolon sits inside quotes. Itsnoteholds a line break. - Row 3 has a NULL
note, because an unquoted empty field means NULL in CSV mode. The next chapter on NULLs covers this rule in detail.
The first line is consumed by HEADER true. Its names are never compared to the table's columns.
Now the backslash-escape variant. Add this to the same script, after the SELECT:
TRUNCATE demo;
COPY demo FROM STDIN
WITH (FORMAT csv, HEADER true, ESCAPE '\');
id,name,note
1,Widget,"Says \"hello\""
\.
SELECT id, name, note FROM demo;The result is the same value as before, Says "hello", read from a different spelling. Here the delimiter is the default comma, so DELIMITER is left out.
ENCODING
A file is just bytes. ENCODING tells COPY which character encoding those bytes use. Without it, COPY uses the current client encoding, which you can check with SHOW client_encoding;. Data is converted between the file encoding and the database encoding as it moves.
\copy products FROM 'products_latin1.csv' WITH (FORMAT csv, HEADER true, ENCODING 'LATIN1')If the file does not match the declared or assumed encoding, the load fails. A typical message is invalid byte sequence for encoding "UTF8": 0xe9. The byte 0xe9 is é in Latin-1, which is not valid UTF-8 on its own. To find a file's encoding, file -i products.csv gives a hint, but it is a guess. You may need to confirm with the file's producer.
Two practical notes:
- A UTF-8 byte order mark (BOM) at the start of a file is not stripped. With
HEADER truethe BOM is inside the discarded header line, so it does no harm. Without a header it becomes part of the first field of the first row. That often breaks an integer or date conversion. - On export, set
ENCODINGto match what the consumer expects. Some older Windows tools expectWIN1252rather than UTF-8.
Forcing quotes on output
By default COPY TO quotes only the fields that need it. FORCE_QUOTE quotes chosen columns always, or all of them with *:
COPY (SELECT id, name, price FROM products ORDER BY id) TO STDOUT
WITH (FORMAT csv, HEADER true, FORCE_QUOTE (name));Here the name column is always quoted, while id and price follow the default rules. This is useful for consumers that treat unquoted text differently from quoted text. NULLs are never quoted by FORCE_QUOTE; they remain an empty, unquoted field.
Two input-side relatives exist, FORCE_NOT_NULL and FORCE_NULL, which change how empty fields convert to NULL. They belong to the NULL chapter.
Reference: defaults in CSV mode
| Option | Applies to | Default | Notes |
|---|---|---|---|
| `FORMAT` | both | `text` | Set `csv` explicitly |
| `HEADER` | both | `false` | `MATCH` is allowed on `COPY FROM` in PostgreSQL 15+ |
| `DELIMITER` | both | comma (CSV) | Single one-byte character |
| `QUOTE` | both, CSV only | `"` | Single one-byte character |
| `ESCAPE` | both, CSV only | same as `QUOTE` | Single one-byte character |
| `ENCODING` | both | client encoding | Name of the file's encoding |
| `FORCE_QUOTE` | `COPY TO`, CSV only | none | Column list or `*` |
Common errors and what they mean
missing data for column "x"or all data landing in one column: wrong delimiter, orFORMAT csvwas omitted.extra data after last expected column: an unquoted delimiter inside a value, or a file with more columns than the table (or the column list).invalid input syntax for type ...on the first row: the header row was read as data. AddHEADER true.unterminated CSV quoted field: a quote opened and never closed. Often the file uses backslash escapes butESCAPEwas not set, so\"closed the field early.invalid byte sequence for encoding: the file's encoding doesn't match. SetENCODING.
In every case COPY aborts the whole statement, so no partial rows remain. Error handling has its own chapter.
Exercise
A vendor sends a file that begins with the line sku;title;remark, uses semicolons as separators, and writes embedded quotes as \" inside double-quoted fields. Write the COPY options (the contents of the WITH list) to load it into a table with three columns, and name one extra check you can add on PostgreSQL 15+.
Show answer
WITH (FORMAT csv, HEADER true, DELIMITER ';', QUOTE '"', ESCAPE '\'). Because the escape character is a backslash, ESCAPE '\' is required; without it the default doubling convention applies and \" would end the quoted field early. On PostgreSQL 15 and later, use HEADER match instead of HEADER true so COPY verifies that the header names sku, title, and remark equal the table's column names in order.
Exercise
You run COPY products FROM '/var/lib/postgresql/import/products.csv' WITH (HEADER true); on a normal comma-separated file with three or more columns. What error do you expect, and what is the fix?
Show answer
Without FORMAT csv, COPY uses the text format, which expects tab-separated fields, so each whole line lands in the first column. COPY then fails with an error like "missing data for column" (or an invalid input syntax error for the first column's type). The fix is to add FORMAT csv: WITH (FORMAT csv, HEADER true).