Sub topic 7
Loading into a subset or different order of columns
This chapter assumes you can run COPY ... FROM and \copy with the CSV options from earlier chapters. You should also know what a column default is and how INSERT ... SELECT works. The examples use the products table from the start of the tutorial.
How COPY matches fields to columns
A CSV file has no column names that COPY can rely on. COPY matches file fields to table columns by position only. Without a column list, field 1 goes to the table's first column, field 2 to the second, and so on, in the order the columns were defined. The file must have exactly as many fields as the table has columns.
A column list changes that rule. You name the target columns in parentheses after the table name, and COPY maps field 1 to the first name in the list, field 2 to the second, and so on. The list order is the file order. The table's own column order no longer matters.
COPY products (name, id, price) FROM '/var/lib/postgresql/import/reordered.csv'
WITH (FORMAT csv, HEADER true);This reads each line as name, id, price, even though products defines id first.
Reordering columns
Suppose a colleague sends reordered.csv with the fields in a different order than your table:
name,id,price
Desk lamp,1,24.50
Notebook,2,3.75Load it from your own machine with \copy:
\copy products (name, id, price) FROM 'reordered.csv' WITH (FORMAT csv, HEADER true)The file's header line is only skipped. HEADER true does not read the names and match them to columns, so the header could say anything and the load would behave the same. The column list is the only thing that decides the mapping.
Check the result:
SELECT * FROM products ORDER BY id; id | name | price | released | notes
----+------------+-------+----------+-------
1 | Desk lamp | 24.50 | |
2 | Notebook | 3.75 | |Each file field was converted to the type of the column it was mapped to. The text 24.50 became a numeric(10,2) because the third list entry is price.
Loading a subset of columns
The column list does not have to include every table column. Columns you leave out are not read from the file. COPY fills each one with its default value, the same as an INSERT that omits the column. If the column has no DEFAULT, the value is NULL.
The released and notes columns in the example above are NULL for this reason. A column with a default behaves differently. Add one to see it:
ALTER TABLE products
ADD COLUMN imported_at timestamptz NOT NULL DEFAULT now();Load a file that has only id and name:
id,name
3,Stapler
4,Paper clips\copy products (id, name) FROM 'short.csv' WITH (FORMAT csv, HEADER true)Rows 3 and 4 get NULL in price, released, and notes. They get the current time in imported_at. Sequence-backed columns work the same way. If id were serial or an identity column, leaving it out of the list would make COPY draw the next value from the sequence for each row.
Two rules follow from this:
- A column that is
NOT NULLwith no default must be in the list. Otherwise every row fails with a not-null violation. - You cannot list generated columns. The server computes their values, so leave them out of the list.
The file must match the list exactly
The number of fields on every line must equal the number of columns in the list. COPY does not ignore extra fields and does not pad short lines. A mismatch raises an error and the whole load fails, as the error-handling chapter explains.
| Situation | Typical error message |
|---|---|
| Line has fewer fields than the list | `missing data for column "price"` |
| Line has more fields than the list | `extra data after last expected column` |
| Field text does not fit the column type | `invalid input syntax for type numeric: "abc"` |
| Required column left out of the list | `null value in column "name" violates not-null constraint` |
The error message includes the line number and the offending line, which makes these easy to find.
Wrong order that still loads
The dangerous case is a wrong mapping that raises no error. If two columns have compatible types, COPY happily puts the data in the wrong one. Suppose a file has id, notes, name but you write (id, name, notes). Both name and notes are text, so every row loads with the two values swapped. Nothing fails.
Protect yourself with a quick check after the first load of a new file format:
SELECT id, name, notes FROM products ORDER BY id LIMIT 5;Read a few rows and ask whether the values look right. You can also try the load inside a transaction and roll back if the rows look wrong:
BEGIN;
\copy products (id, notes, name) FROM 'swapped.csv' WITH (FORMAT csv, HEADER true)
SELECT id, name, notes FROM products ORDER BY id LIMIT 5;
ROLLBACK;HEADER MATCH on PostgreSQL 15 and later
From PostgreSQL 15 on, COPY FROM accepts HEADER match instead of HEADER true. COPY then checks that the first line of the file contains the same column names as the column list, in the same order, and fails if they differ. When it applies, this catches most of the silent swaps described above.
\copy products (name, id, price) FROM 'reordered.csv' WITH (FORMAT csv, HEADER match)If the header says id,name,price, this command fails instead of loading swapped data. The comparison is case-sensitive. The check only works if the sender's header names are the same as your column names, which is often not true for files from other systems. On older servers, use HEADER true and verify by eye.
When the file has columns you do not want
A column list can leave out table columns, but it cannot skip file fields. If the file has five fields per line, the list needs five names. So what if the file contains a column you do not want to store, or needs a transformation before it fits your table?
There are three common answers:
- Use a staging table that mirrors the file, then
INSERT ... SELECTthe columns you want. - Pre-process the file with a command-line tool such as
cutorawkbefore loading it. This works for simple files but is risky with CSV, because quoted fields can contain delimiters and newlines. - Use
COPY ... FROM PROGRAMto run such a tool on the server. This needs elevated privileges, covered in the security chapter.
The staging approach is the most reliable because the database does the parsing. Here a vendor sends vendor.csv:
id,name,vendor_code,price,list_date
10,Whiteboard,V-88,45.00,15/03/2024
11,Marker set,V-91,8.20,It has a vendor_code your table has no column for, and a date written as day/month/year. Load the file as-is into a temporary table whose columns match the file, with the date kept as text:
CREATE TEMP TABLE vendor_stage (
id integer,
name text,
vendor_code text,
price numeric(10,2),
list_date text
);
\copy vendor_stage FROM 'vendor.csv' WITH (FORMAT csv, HEADER true)
INSERT INTO products (id, name, price, released, notes)
SELECT id,
name,
price,
to_date(list_date, 'DD/MM/YYYY'),
'vendor code ' || vendor_code
FROM vendor_stage;The INSERT ... SELECT is where you choose columns, reorder them, rename them, and convert values. The empty list_date in the second row is read as NULL, since an unquoted empty field is NULL in CSV format. to_date(NULL, ...) returns NULL, so the row loads with no release date. The next chapter on staging tables builds on this pattern with cleanup and upserts.
Column lists in COPY TO
Column lists work for exports too. They choose which columns to write and in which order:
\copy products (name, price) TO 'names_and_prices.csv' WITH (FORMAT csv, HEADER true)With HEADER true, the first line of the output contains the listed column names. If you need computed or renamed output columns, use a query instead of a table, as in the export chapter:
\copy (SELECT name AS product, price AS list_price FROM products ORDER BY id) TO 'renamed.csv' WITH (FORMAT csv, HEADER true)The header then uses the aliases product and list_price.
Options that refer to columns
Some COPY options take column names. They must be columns that appear in the column list:
FORCE_NOT_NULL (col, ...)stops a column from converting the NULL string to NULL, so an empty field stays an empty string in a text column.FORCE_NULL (col, ...)does the reverse for quoted values that match the NULL string.
If you add a column to one of these options but leave it out of the list, COPY reports an error. When you subset columns, keep the two lists consistent.
\copy products (id, name, notes) FROM 'notes.csv' WITH (FORMAT csv, HEADER true, FORCE_NOT_NULL (notes))This load stores an empty notes field as '' instead of NULL.
Choosing an approach
| Your file | Use |
|---|---|
| Same fields as the table, same order | No column list needed, but a list is still safer if the table may change |
| Same fields, different order | A column list in file order |
| Fewer fields than the table | A column list of the fields present; the rest get defaults |
| More fields than you need | A staging table, then `INSERT ... SELECT` |
| Fields needing conversion (dates, units, text splitting) | A staging table with text columns, then convert in SQL |
Writing the column list even when it is not required is good practice. A script that relies on table order breaks when someone later adds a column to the table with ALTER TABLE. A script with an explicit list keeps working, and the new column gets its default.
Putting it together
Here is a complete script that loads a reordered file, leaves several columns to their defaults, and checks the result. It runs from a shell and uses the verification idea from earlier chapters:
psql "$DATABASE_URL" -c "\copy products (name, id, price) FROM 'reordered.csv' WITH (FORMAT csv, HEADER true)"
psql "$DATABASE_URL" -c "SELECT id, name, price, released, notes FROM products WHERE id IN (1, 2) ORDER BY id"If the output shows names in name and numbers in id, the mapping is right.
Exercise
A file items.csv has the header price,id,name. Your products table is defined as (id, name, price, released, notes). Write the \copy command that loads it, and say what values released and notes get.
Show answer
\copy products (price, id, name) FROM 'items.csv' WITH (FORMAT csv, HEADER true). The list follows the file's field order, not the table's. released and notes are not in the list, so each gets its column default. These columns have no DEFAULT, so both are NULL.
Exercise
A file has five fields per line: id,name,price,released,supplier. The table has no supplier column. Why does \copy products (id, name, price, released) FROM 'f.csv' WITH (FORMAT csv, HEADER true) fail, and how do you load the file?
Show answer
COPY cannot skip file fields. Each line has five fields and the list has four, so COPY reports extra data after last expected column. Create a temporary staging table with all five columns (for example CREATE TEMP TABLE items_stage (id integer, name text, price numeric(10,2), released date, supplier text)). Load the file into it with \copy, then run INSERT INTO products (id, name, price, released) SELECT id, name, price, released FROM items_stage.
Exercise
You load a file whose fields are id, notes, name using the list (id, name, notes). Both columns are text. Does COPY report an error? How can you detect the problem?
Show answer
No error occurs, because both columns accept any text. Every row ends up with name and notes swapped. Detect it by selecting a few rows after the load and reading them, by running the load inside BEGIN ... ROLLBACK first, or on PostgreSQL 15 and later by using HEADER match so COPY checks the header names against the list.