Sub topic 3
Importing a CSV File with `COPY FROM`
This chapter assumes basic SQL, PostgreSQL data types, the psql command-line client, and the structure of a CSV file. You will use an existing table and load rows from a CSV file into it.
What `COPY FROM` Does
COPY FROM is PostgreSQL's bulk-loading command. It reads records from a file or input stream and inserts them into a table. It is usually faster and simpler than sending one INSERT statement for every row because PostgreSQL processes the data as a continuous load.
Start with this table:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);Suppose products.csv contains:
id,name,price,released,notes
1,Keyboard,49.99,2026-01-15,Wireless
2,Mouse,19.50,2026-02-01,
3,"Desk, small",125.00,2026-02-20,"Fits a narrow room"The first line contains column names. The third product demonstrates that a comma inside a value must be quoted.
Loading a CSV File
The SQL COPY command reads a file on the database server:
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);FORMAT csv selects PostgreSQL's CSV parser. HEADER true tells PostgreSQL to skip the first input line. The remaining fields are converted to the types of the destination columns. For example, 49.99 is converted to numeric(10,2), and 2026-01-15 is converted to date.
The path must be readable by the PostgreSQL server process. A path on your laptop is not necessarily a path on the database server.
In psql, use \copy when the file is on the computer running psql:
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)\copy reads the file on the client and sends its contents through the database connection. This often avoids server filesystem permissions and is convenient for local imports.
Mapping Columns Explicitly
An explicit column list documents the file's order and protects you from changes to the table definition:
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)The first field goes to id, the second to name, and so on. The file does not need to contain every table column. For example, a table can provide a default for an omitted column:
ALTER TABLE products
ADD COLUMN imported_at timestamptz DEFAULT current_timestamp;
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)The imported_at value is generated for each inserted row. The listed columns must match the file's field order.
Handling Separators and Missing Values
CSV files do not always use commas. You can describe a semicolon-separated file and define how it spells a missing value:
\copy products FROM 'products.csv'
WITH (
FORMAT csv,
HEADER true,
DELIMITER ';',
NULL 'NULL',
QUOTE '"'
)With NULL 'NULL', an unquoted field containing exactly NULL becomes SQL NULL. In standard CSV mode, an empty unquoted field also represents NULL, while a quoted empty field, "", represents an empty text string.
Quoted fields can contain delimiters, line breaks, and quote characters. A quote inside a quoted field is normally written as two quotes, such as "Sam ""Ace"" Lee".
Transactions and Common Errors
A COPY operation runs as one statement. If a row violates a type conversion, NOT NULL constraint, or unique constraint, PostgreSQL normally aborts the entire COPY. Rows loaded earlier in the same operation are rolled back.
On PostgreSQL 17 and later, ON_ERROR ignore skips rows whose values cannot be converted to the target column type:
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, ON_ERROR ignore);This option does not make every constraint violation safe to ignore. Validate the rejected or skipped data separately when accuracy matters.
Common causes of failure include:
- The header option is missing, so PostgreSQL tries to convert
idto an integer. - The file's field order differs from the table order.
- A delimiter or quote character does not match the file.
- A date or number uses a format PostgreSQL cannot convert.
- A duplicate primary key already exists.
- The server cannot access the path used by
COPY.
Exercise
A CSV file has columns in the order name, id, price, but the table order is id, name, price. What should you change in the COPY command?
Show answer
Add an explicit destination column list in the file's order: COPY products (name, id, price) FROM 'products.csv' WITH (FORMAT csv, HEADER true);