Sub topic 3
Loading into a Subset or Different Order of Columns
This chapter assumes you know basic SQL, can use psql, and have the products table from the plan. You will map file columns to table columns, load through a staging table, handle bad rows, verify the result, and speed up large loads.
Mapping file columns to table columns
A column list after the table name tells COPY which table columns receive the fields, in file order. The header line is skipped, but its names are not used for matching.
\copy products (name, id) FROM 'products_reordered.csv' WITH (FORMAT csv, HEADER true)Table columns that are not listed take their default value or NULL.
Privileges for server-side files
Server-side COPY ... FROM 'file' reads from the database server's disk. The role needs superuser rights or the pg_read_server_files role. Writing a server file with COPY ... TO requires pg_write_server_files. \copy reads the client's files and needs neither.
Staging tables and upserts
A staging table lets you clean rows before they reach the real table. Duplicate id values in the staging table cause an error during the upsert, so remove them first.
CREATE TEMP TABLE products_stage (LIKE products);
\copy products_stage (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)
INSERT INTO products
SELECT * FROM products_stage
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, price = EXCLUDED.price,
released = EXCLUDED.released, notes = EXCLUDED.notes;When rows fail
A single COPY statement is atomic. One bad row aborts the whole load, and nothing is stored. On PostgreSQL 17 and later, ON_ERROR ignore skips rows whose values cannot convert to the column type. Earlier versions do not support this option, so check your server version first.
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, ON_ERROR ignore);Verifying and round-tripping
Export the table, reload the file into a scratch table, and compare. The wc -l count includes the header line, so subtract one unless quoted fields contain line breaks.
psql "$DATABASE_URL" -c "\copy (SELECT * FROM products ORDER BY id) TO 'products_export.csv' WITH (FORMAT csv, HEADER true)"
psql "$DATABASE_URL" -c "SELECT count(*) FROM products"
wc -l products_export.csvCREATE TEMP TABLE rt (LIKE products);
\copy rt FROM 'products_export.csv' WITH (FORMAT csv, HEADER true)
SELECT count(*) FROM (SELECT * FROM products EXCEPT SELECT * FROM rt) d; -- expect 0Speeding up large loads
Load into an empty or truncated table. Drop non-essential indexes before the load and rebuild them afterward. Raise maintenance_work_mem for the index builds. FREEZE true works only when the table was created or truncated in the same transaction.
Exercise
A file has columns in the order name, id, but the table's columns are id, name. Which \copy command loads the file correctly?
Show answer
\copy products (name, id) FROM 'file.csv' WITH (FORMAT csv, HEADER true)