Sub topic 10
When rows fail: atomic loads and ON_ERROR
This chapter assumes you can run COPY FROM and \copy with the CSV options from earlier chapters. You should also know what a transaction is and how PostgreSQL data types work. Here you will learn what happens when one row in a large file is bad, why that is usually a good thing, and what to do when it gets in your way.
COPY is all or nothing
COPY FROM is a single SQL statement, and PostgreSQL runs every statement atomically. Either all rows from the file become part of the table, or none of them do. If row 9,999 of 10,000 cannot be converted to the column type, the first 9,998 rows are rolled back too.
Take this table and file:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);id,name,price,released,notes
1,Widget,9.99,2024-01-15,
2,Gadget,abc,2024-02-01,price typo
3,Gizmo,24.50,2024-03-10,Loading it fails on line 3 of the file (the second data row):
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)The server answers with an error like this:
ERROR: invalid input syntax for type numeric: "abc"
CONTEXT: COPY products, line 3, column price: "abc"Afterwards SELECT count(*) FROM products returns 0. Row 1 was valid, but it is gone as well.
Reading the error message
The CONTEXT line tells you three things:
- The line number counts lines in the file, and the header counts as line 1. A bad value in the first data row is therefore reported as line 2.
- The column name is the table column that failed. With a column list, it is the table column the field was mapped to, not a header from the file.
- The offending text is quoted. For a long or multi-line field, it may be shortened.
The error reports only the first bad row. A file with 50 bad rows takes 50 fix-and-retry cycles unless you check the data another way. That cost is the main reason the techniques below exist.
Why atomic behavior is useful
All-or-nothing loading protects you from a half-loaded table. If a load stops partway, you do not have to work out which rows made it in. Fix the file and run the same command again.
This only holds if the table was in a known state before the load. If it was not empty, a retry after a partial success would create duplicates, but an atomic COPY never partially succeeds. Rerunning is safe.
What a failed COPY leaves behind
A rolled-back load is not completely invisible:
- The rows that were already written are dead tuples. They take disk space until
VACUUMreclaims them. A failed load of a very large file can leave noticeable bloat. - Sequences advance. If a column default calls
nextval(), the numbers used during the failed load are not given back. Gaps in a serial column are normal and harmless, but do not rely on gap-free numbering. - Triggers and the write-ahead log have already done their work. Anything a trigger did outside the transaction, such as sending a notification through an external system, is not undone.
Failure inside a larger transaction
If you run COPY inside BEGIN ... COMMIT, a failure puts the whole transaction into an aborted state. Every following statement is rejected with current transaction is aborted, commands ignored until end of transaction block until you run ROLLBACK. Use a savepoint if you want to recover without losing the earlier work:
BEGIN;
INSERT INTO products (id, name) VALUES (100, 'Before the load');
SAVEPOINT before_copy;
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)
-- if the COPY fails, undo only the COPY:
ROLLBACK TO SAVEPOINT before_copy;
COMMIT;After ROLLBACK TO SAVEPOINT, the transaction is usable again, and the earlier INSERT is kept.
What kinds of errors stop a load
| Problem | Example | Result |
|---|---|---|
| Value cannot be converted to the column type | `abc` in a `numeric` column, `2024-13-45` in a `date` column | Error, whole load rolled back |
| Constraint violation | NULL in a `NOT NULL` column, duplicate primary key, failed `CHECK` | Error, whole load rolled back |
| Wrong number of fields in a row | 4 fields in a 5-column file | Error, whole load rolled back |
| Encoding problem | Bytes that are invalid in the client encoding | Error, whole load rolled back |
| Unterminated quoted field | A `"` that is never closed | Error, usually reported at the end of the data |
Constraint errors matter most for upserts. COPY has no ON CONFLICT clause, so a single duplicate key aborts the load. The staging table pattern from the previous chapter addresses that case.
ON_ERROR in PostgreSQL 17 and later
PostgreSQL 17 added the ON_ERROR option to COPY FROM. It has two values:
stopis the default. It keeps the behavior described above: the first error aborts the statement.ignoreskips rows that fail during conversion of a field to its column type, and continues.
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, ON_ERROR ignore);With the sample file above, this loads rows 1 and 3 and skips row 2. When it finishes, the server sends a notice with the count of skipped rows:
NOTICE: 1 row was skipped due to data type incompatibility
COPY 2Note that the command tag says COPY 2: it counts only the rows that were inserted.
The limits of ignore
ON_ERROR ignore is narrower than it sounds. Treat it as "skip values that do not parse as the target type" and nothing more:
- Constraint violations (
NOT NULL,UNIQUE,CHECK, foreign keys) still abort the whole load, because they are raised after conversion, when the row is inserted. - Structural problems with a row, such as the wrong number of fields, are outside what the 17 release documents for
ignore. Test with your own data and check the documentation for your version before depending on it. - It exists only for
COPY FROM.COPY TOhas no equivalent. - It does not apply to binary format files.
Skipping is also silent about which rows were lost. The default output gives you a count, not the content. PostgreSQL 17 adds a LOG_VERBOSITY option. Setting it to verbose makes the server send a notice for each skipped row, with its line number and column:
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose);Newer releases add more error-handling options, such as a limit on how many rows may be skipped. If you run a version later than 17, read the COPY page for it.
Choosing between stop and ignore
Prefer stop when the file is supposed to be clean, such as an export from another system you control. A failure then tells you something is wrong upstream. Use ignore when the data is known to be messy, you can tolerate losing the bad rows, and you will look at what was skipped. A typical case is scraped or user-submitted data where a few rows are expected to be garbage.
Handling bad rows on any version
Before PostgreSQL 17, and whenever you need to know exactly which rows are bad, load everything as text first. A text column accepts any value, so conversion cannot fail. You then find the bad rows with SQL.
CREATE TEMP TABLE products_raw (
id text,
name text,
price text,
released text,
notes text
);
\copy products_raw FROM 'products.csv' WITH (FORMAT csv, HEADER true)
-- Rows whose price is not a plain decimal number
SELECT id, name, price
FROM products_raw
WHERE price IS NOT NULL
AND price !~ '^[0-9]+(\.[0-9]+)?$';When the problem rows are fixed or removed, cast and insert the rest:
INSERT INTO products (id, name, price, released, notes)
SELECT id::integer, name, price::numeric, released::date, notes
FROM products_raw
WHERE price IS NULL OR price ~ '^[0-9]+(\.[0-9]+)?$';This takes more typing than ON_ERROR ignore, but it has real advantages. You see every bad row, not only the first. You choose whether to repair or drop each one. Constraint problems such as duplicate ids can be handled in the same INSERT with ON CONFLICT.
A reusable checklist
- Run the load without
ON_ERRORfirst on a copy of the data. The first error often points to a systematic problem such as a wrong delimiter or missingHEADER true, rather than one bad row. - If the errors are scattered bad values, decide whether you can afford to lose those rows. If yes and you are on 17 or later, use
ON_ERROR ignorewithLOG_VERBOSITY verbose. - If you cannot lose rows, or need to repair them, load into a text staging table and fix them in SQL.
- Wrap the load in a transaction or savepoint if other changes must succeed or fail with it.
- Compare row counts afterwards: the rows in the file, the rows inserted, and the rows skipped should add up.
Exercise
A file has 1,000 data rows plus a header. Row 400 has the text n/a in an integer column. You run COPY FROM with HEADER true on PostgreSQL 16, and then on PostgreSQL 17 with ON_ERROR ignore. How many rows does the table contain after each run, assuming it started empty and no other row has a problem? What does the 17 run report?
Show answer
On PostgreSQL 16 the load fails and rolls back, so the table has 0 rows. On PostgreSQL 17 with ON_ERROR ignore the bad row is skipped, so the table has 999 rows. The 17 run sends a notice that one row was skipped due to data type incompatibility, and the command tag is COPY 999.
Exercise
You use ON_ERROR ignore, and the file contains a row whose id duplicates an existing primary key. What happens, and which approach would let you load the other rows?
Show answer
The load aborts and rolls back everything, because a unique violation is a constraint error and ON_ERROR ignore covers only data type conversion errors. To load the other rows, copy the file into a staging table with no unique constraint, then INSERT ... SELECT into the real table with ON CONFLICT (id) DO NOTHING or DO UPDATE.
Exercise
Inside a transaction you run a COPY that fails, and then run SELECT 1. The SELECT is rejected. How do you keep the work done earlier in the transaction?
Show answer
Create a savepoint before the COPY, and after the failure run ROLLBACK TO SAVEPOINT with that savepoint's name. This undoes only the failed COPY and makes the transaction usable again, so earlier statements are preserved and you can COMMIT.