Sub topic 3
Importing a CSV file with COPY FROM
This chapter shows how to load a CSV file into an existing table with COPY ... FROM. It covers what the command does with each line, the options you need most often, and how to read its error messages.
It assumes you can write CREATE TABLE, INSERT and SELECT, that you use psql, and that you know the basic PostgreSQL types (integer, numeric, date, text). The previous chapter described the CSV format options. This chapter uses them.
The target table and the file
The examples use the products table from earlier in the tutorial.
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);The sample file is products.csv. It has a header line, a quoted field that contains a comma, a quoted field that contains escaped quotes, and some empty fields.
id,name,price,released,notes
1,Desk lamp,24.50,2024-03-01,
2,"Notebook, A5",3.20,2024-05-12,"Pack of ""5"""
3,Pen,,2024-06-30,What COPY FROM does
COPY table FROM source reads rows from a file, or from the client connection, and appends them to the table. It never replaces existing rows. If you run it twice on the same file, you load every row twice, or fail on the primary key if one exists.
For each line, PostgreSQL does the following:
- It splits the line into fields using the delimiter and quote rules.
- It converts each field's text into the column's data type.
- It fills any column that has no field with its default value.
- It runs
BEFORE ROWtriggers, then checks constraints such asNOT NULL,CHECK, unique keys and foreign keys. - It writes the row.
Triggers and constraints still apply. COPY is faster than a series of INSERT statements because it skips per-statement parsing and planning and sends data in a continuous stream. It does not skip your data rules.
The basic command
This is the server-side form. The file is read by the database server process, so the path refers to the server's filesystem.
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);On success, psql prints a command tag with the number of rows loaded:
COPY 3Each option in the WITH list does one job:
FORMAT csvselects the CSV rules. The default format is PostgreSQL's own text format, which is tab-delimited and uses backslash escapes. It is not CSV, so loading a CSV file without this option fails or produces wrong data.HEADER truetellsCOPYto discard the first line of the file. It does not read the header names or use them to match columns. By default the file's fields are matched to table columns by position only.
The older syntax without parentheses (COPY products FROM '...' CSV HEADER) still works. Use the parenthesized form. It is the only one that accepts every option.
How the CSV rules read the sample file
With FORMAT csv, the defaults give these results for products.csv:
| Input in the file | Result in the table |
|---|---|
| `1,Desk lamp,24.50,2024-03-01,` | `notes` is `NULL`, because an unquoted empty field is `NULL` in CSV format |
| `"Notebook, A5"` | The name `Notebook, A5`. The comma is inside quotes, so it is not a delimiter |
| `"Pack of ""5"""` | The text `Pack of "5"`. Inside a quoted field, a doubled quote stands for one quote |
| `3,Pen,,2024-06-30,` | `price` is `NULL` |
A quoted empty field ("") is different. It loads as an empty string, not NULL. The NULL chapter covers this in detail.
Running it from the client with \copy
A server-side COPY needs a file the server can read, and a role allowed to read it. On a managed database or a remote server, you usually have neither. The psql meta-command \copy reads the file on your machine and sends it over the connection.
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)The explicit column list says which table columns the file's fields map to, in order. The file must have exactly that many fields on every line.
\copy is a psql command, not SQL. It must be on a single line, with no trailing semicolon. Relative paths resolve against psql's working directory. The next chapter compares the two forms in more detail.
Matching the file's layout
A file rarely matches the defaults. Three options handle most differences.
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true, NULL 'NULL', DELIMITER ';', QUOTE '"')DELIMITER ';'sets the field separator to a semicolon. The delimiter must be a single one-byte character.NULL 'NULL'makes the literal textNULLmean a missing value. Once you set this, an unquoted empty field is no longerNULL. It is an empty string, which is an error for anumericordatecolumn.QUOTE '"'sets the quoting character. Double quote is already the default, so here it only makes the setting explicit.
If the file is not in the database's client encoding, add ENCODING 'LATIN1' (or whichever encoding applies). In psql, \encoding sets the client encoding for the session. Without the right encoding, you get invalid byte sequence errors or garbled characters.
Dates and numbers
COPY converts text with the same input functions as a literal in SQL. ISO dates such as 2024-03-01 always work. A date like 03/01/2024 is read according to the session's DateStyle setting, so it can mean March 1 or January 3. Check the setting with SHOW datestyle;, or change the file to ISO format. Numbers must not contain thousands separators or currency symbols. 1,200.50 is two fields in a comma-delimited file, and $24.50 is not a valid numeric.
Atomic loads and reading errors
A COPY FROM is one statement, so it is all-or-nothing. If line 50,000 of a 50,000-line file has a bad value, the statement fails and none of the rows are kept. No partial import is left behind to clean up.
Suppose line 3 of the file has abc in the id column. PostgreSQL reports:
ERROR: invalid input syntax for type integer: "abc"
CONTEXT: COPY products, line 3, column id: "abc"The CONTEXT line gives the line number, counting the header, and the column name. These are the errors you will see most often:
| Message | Usual cause |
|---|---|
| `invalid input syntax for type ...` | The value cannot convert to the column type, such as text in a numeric column or an unrecognized date |
| `missing data for column "notes"` | A line has fewer fields than expected. Often a stray line break inside an unquoted field |
| `extra data after last expected column` | A line has more fields than the table or column list. Often an unquoted delimiter inside a value |
| `null value in column "name" violates not-null constraint` | An empty field was loaded into a `NOT NULL` column |
| `duplicate key value violates unique constraint` | The file contains an `id` that already exists in the table, or twice in the file |
| `could not open file ... for reading: Permission denied` | The server process cannot read the path, or the file is on a different machine than the server |
Two details are easy to miss. Rows from a failed COPY are invisible, but they still take up disk space until VACUUM reclaims it. Also, COPY stops at the first error, so a file with many problems takes many runs to fix.
Skipping bad rows on PostgreSQL 17 and later
From PostgreSQL 17, ON_ERROR ignore skips rows whose values cannot be converted to the column type, instead of aborting the load.
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, ON_ERROR ignore);The option only covers type-conversion failures. Constraint violations such as NOT NULL or duplicate keys still abort the whole statement. On earlier versions, the option does not exist and the command fails with a syntax error. After a load with this option, check the server's notice about how many rows were skipped. A silent partial import is hard to notice later.
A first check after loading
The command tag tells you how many rows were loaded. Compare it with the file. A CSV with a header has one more line than it has rows, as long as no quoted field contains a line break.
psql "$DATABASE_URL" -c "\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)"
psql "$DATABASE_URL" -c "SELECT count(*) FROM products"
wc -l products.csvFor the sample file, the table has 3 rows and wc -l reports 4. Line breaks inside quoted fields make wc -l overcount, so treat a mismatch as a reason to look, not as proof of lost data. A later chapter covers verification in full.
Common mistakes
- Forgetting
HEADER true.COPYthen tries to loadid,name,price,...as data, and the first line fails withinvalid input syntax for type integer: "id". - Using
HEADER trueon a file with no header. The first data row is silently thrown away. The row count is off by one and no error appears. - Loading into a table that already has data.
COPY FROMappends. To replace the contents,TRUNCATEfirst, inside the same transaction. - Using a client path with server-side
COPY.COPY ... FROM '/home/me/products.csv'looks for that path on the server. Use\copyfor files on your own machine. - Using a semicolon with
\copy.\copyends at the line break. A trailing;is treated as part of the command and produces a syntax error.
Exercises
Exercise
You run \copy products FROM 'products.csv' WITH (FORMAT csv) on a file that has a header line, and it fails with invalid input syntax for type integer: "id". What is wrong, and what is the fix?
Show answer
Without HEADER true, COPY treats the first line as data and tries to load the text id into the integer column id. Add HEADER true to the options: WITH (FORMAT csv, HEADER true).
Exercise
A semicolon-delimited export uses the text NULL for missing values. You load it with WITH (FORMAT csv, HEADER true, DELIMITER ';') and get an error on a numeric column. Why does this happen, and which option fixes it?
Show answer
Without a NULL option, CSV format treats only an unquoted empty field as NULL. The text NULL is passed to the numeric input function as an ordinary string and fails. Add NULL 'NULL' so the text NULL loads as a missing value.
Exercise
A 100,000-line load aborts at line 70,001 with a bad date. How many of the earlier rows are in the table afterwards, and what can you do on PostgreSQL 17 to continue past such rows?
Show answer
None. COPY FROM is a single statement and rolls back completely on an error. On PostgreSQL 17 and later you can add ON_ERROR ignore to skip rows with values that cannot be converted to the column type. Constraint violations still abort the load.