Sub topic 11
Verifying the result and round-tripping data
A COPY that finishes without an error is not proof that the data is right. The load may have taken fewer rows than you expected, the file may have been stale, or a value may have changed form on the way through. This chapter covers checks that catch those problems, and how to confirm that an export can be loaded back into an identical table.
It assumes you can run psql, know the products table from earlier chapters, and understand the CSV options (HEADER, NULL, DELIMITER, QUOTE) and the difference between server-side COPY and client-side \copy.
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);What "verified" means
Verification works at three levels. Each is stronger than the last and costs more.
- Counts. The number of rows in the table matches the number of records in the file.
- Summaries. Aggregates such as sums, null counts, and minimum and maximum values match.
- Full comparison. Every row in the table matches a row in a reference copy, with nothing missing and nothing extra.
Counts are cheap and catch gross errors. Summaries catch value changes that counts miss, such as a price column loaded with the wrong scale. A full comparison finds everything, but it needs a second copy of the data to compare against.
Start with the command tag
Every successful COPY returns a command tag with the number of rows processed. In psql it prints as COPY 1250. \copy prints it too.
COPY 1250This is the first number to check. If the source system said it exported 1,300 records and the tag says 1,250, you already know something is wrong. Write the number down or capture it in scripts. Don't rely on the later SELECT count(*) alone, because on a table that already had rows, the table count includes the old data.
When you load into a table that already contains rows, compare counts before and after, or load into an empty staging table so the table count is the load count.
Counting lines in the file
The wc -l check from the spine counts newline characters. For a file written with HEADER true, a table with N rows normally produces N + 1 lines.
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.csvIf the table holds 1,250 rows, wc -l should print 1251.
The check has two known failure cases:
- Embedded newlines. A quoted field such as a
notesvalue with a line break inside it is one CSV record but two physical lines.wc -lthen reports more lines than records. This is legal CSV, andCOPYwrites and reads it correctly. - Missing final newline. A file produced by another tool may omit the newline after the last record.
wc -lthen counts one fewer line than there are records.
So treat wc -l as a quick sanity check, not as the authority. When it disagrees with the row count, look for multi-line fields before assuming data was lost. A reliable way to count records in a file is to load it and read the COPY tag, or to compare it against a record count supplied by whoever produced the file.
Summary checks
After a load, compute a few aggregates that depend on every row and compare them with known values. The values can come from the source system, from a previous run, or from the file itself using a command-line tool.
SELECT count(*) AS row_count,
count(*) FILTER (WHERE price IS NULL) AS null_prices,
count(*) FILTER (WHERE notes IS NULL) AS null_notes,
sum(price) AS total_price,
min(released) AS first_release,
max(released) AS last_release
FROM products;The null counts are useful because NULL handling is the most common source of silent errors. If the file used the text NULL for missing values and you forgot the NULL 'NULL' option, the notes column would contain the string NULL and null_notes would be zero. A date or number column would reject the text and the load would fail, but a text column accepts it quietly.
A second useful check looks for values that should not exist:
SELECT count(*) AS suspicious
FROM products
WHERE notes IN ('NULL', 'null', 'N/A', '')
OR name <> btrim(name);A non-zero result points to a missed NULL option, an empty string where you wanted NULL, or unwanted whitespace.
The round trip
A round trip means exporting a table to CSV, loading the file into a fresh table of the same shape, and confirming that the two tables hold the same data. It tests your chosen options in both directions at once. If the export and import options disagree, the comparison shows it.
CREATE TEMP TABLE products_check (LIKE products);
\copy (SELECT * FROM products ORDER BY id) TO 'products_export.csv' WITH (FORMAT csv, HEADER true)
\copy products_check FROM 'products_export.csv' WITH (FORMAT csv, HEADER true)LIKE products copies the column names, types, and NOT NULL constraints, but not the primary key. Without the key, duplicate rows in the file would load, and the comparison below would reveal them.
Temporary tables belong to one session. Put the whole script in a file and run it with psql -f, so every statement shares the session. Also keep each \copy command on a single line, because psql meta-commands end at the line break.
Comparing the two tables
EXCEPT ALL returns the rows of the first query that are missing from the second, counting duplicates. Run it in both directions and combine the results:
SELECT 'only in products' AS side, p.*
FROM (SELECT * FROM products EXCEPT ALL SELECT * FROM products_check) AS p
UNION ALL
SELECT 'only in check', c.*
FROM (SELECT * FROM products_check EXCEPT ALL SELECT * FROM products) AS c;An empty result means the tables hold identical rows. Two details matter here:
EXCEPTcompares rows with "not distinct" semantics, so twoNULLvalues count as equal. This is what you want for verification. A join with=would treatNULL = NULLas unknown and report false differences.- Plain
EXCEPTremoves duplicates, so it would hide a row that loaded twice. UseEXCEPT ALLto keep them visible.
For a very large table, you can compare one fingerprint per table instead of listing rows:
SELECT count(*) AS n,
md5(string_agg(t::text, E'\n' ORDER BY id)) AS fingerprint
FROM products AS t;Run the same query against products_check and compare the two results. A matching fingerprint means a match on every column, in order of id. A mismatch tells you only that something differs, so follow it with the EXCEPT ALL query to find what.
What survives a round trip, and what can drift
With the default CSV settings, most types round-trip exactly. The table below lists the cases that need attention.
| Data | Behavior | What to do |
|---|---|---|
| `NULL` | Written as an unquoted empty field and read back as `NULL` | Use the defaults on both sides, or set the same `NULL` string on both |
| Empty string `''` | Written as `""` and read back as an empty string | Don't set `NULL ''` in CSV mode, because it makes the two cases ambiguous |
| `timestamptz` | Written in the session's `TimeZone` and read back as the same instant | Set `TimeZone` explicitly in scripts so exports are reproducible |
| `timestamp`, `date` | Written as text using the `DateStyle` setting | Keep `DateStyle` the same for export and import (`ISO` is the default) |
| `numeric`, `integer` | Written exactly | None |
| `real`, `double precision` | Written with enough digits to read back exactly on current PostgreSQL versions | None on modern servers. Older servers may need `extra_float_digits` set to 3 |
| Text with commas, quotes, or newlines | Quoted automatically | Use the same `QUOTE` and `ESCAPE` options on both sides |
| Text in a non-UTF-8 client encoding | Converted to the client encoding | Set `ENCODING` or `client_encoding` to the same value on both sides |
The first two rows explain why the CSV defaults are safe. Because an empty string is quoted and a missing value is not, the file keeps the distinction, and the load restores it. If you apply a custom NULL string to a file, make sure the same string is used in the import.
A round trip within one database cannot catch every problem. A file that loads cleanly into the same server can still fail in a different environment with another encoding or DateStyle. If the file is bound for another system, run the import check on that system too.
Check the header on import
On PostgreSQL 15 and later, HEADER MATCH makes COPY FROM compare the first line of the file with the column names of the target. The load fails if they differ, so a file with reordered or renamed columns cannot be loaded into the wrong fields by accident.
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER match)Plain HEADER true only skips the first line and never looks at it. With it, a file whose columns were swapped loads without error if the types happen to fit, and verification becomes the only safeguard.
A verification routine for a real load
Put the steps together in one script that stops when a check fails. The \if commands require psql from PostgreSQL 10 or later.
\set ON_ERROR_STOP on
CREATE TEMP TABLE products_stage (LIKE products);
\copy products_stage FROM 'products.csv' WITH (FORMAT csv, HEADER true)
SELECT count(*) AS staged_rows,
count(*) FILTER (WHERE price IS NULL) AS null_prices,
sum(price) AS total_price
FROM products_stage;
SELECT count(*) - count(DISTINCT id) AS duplicate_ids,
count(*) FILTER (WHERE id IS NULL) AS missing_ids
FROM products_stage;Read the output and decide before merging into products. If you want the script to decide for you, test the result with \gset and \if:
SELECT count(*) - count(DISTINCT id) = 0 AS ids_ok FROM products_stage \gset
\if :ids_ok
INSERT INTO products SELECT * FROM products_stage
ON CONFLICT (id) DO NOTHING;
\else
\echo 'Duplicate ids in the file, nothing merged'
\endifThe staging table is what makes this possible. You inspect the data before it touches the real table, which is cheaper than finding problems afterwards and repairing them.
Common mistakes
- Trusting the absence of an error.
COPYaccepts any data that fits the column types, including wrong data. - Comparing against a table that was not empty. Always know the count before the load.
- Forgetting that
ON_ERROR ignorehides rows. On PostgreSQL 17 and later, skipped rows reduce the loaded count. Compare theCOPYtag with the number of records in the file, and read the notice that reports how many rows were skipped. - Verifying with a different session setup.
DateStyle,TimeZone, andclient_encodingchange how values are written and parsed. A round trip run under different settings than production tests nothing useful. - Relying on row order. Tables have no inherent order. Use
ORDER BYfor exports you will diff, and compare sets of rows, not positions.
Exercise
You export a 400-row table with HEADER true and wc -l prints 409 instead of 401. The row count in the table is 400. What is the most likely cause, and how do you confirm that no data was duplicated?
Show answer
Some text values contain embedded newlines, which COPY writes inside quoted fields. Each such field adds a physical line without adding a record, so wc -l overcounts. To confirm, load the file into a temporary table created with LIKE, check that the COPY tag reports 400, and run EXCEPT ALL in both directions against the original table. Empty results in both directions show that nothing was duplicated or lost.
Exercise
A round trip shows that rows with a missing notes value come back with an empty string instead of NULL. The export used WITH (FORMAT csv, HEADER true, NULL '') and the import used WITH (FORMAT csv, HEADER true). Why does this happen, and how do you fix it?
Show answer
In CSV mode, NULL '' makes the export write missing values as an empty field, and it also makes real empty strings indistinguishable from NULL. The import, using the default, reads unquoted empty fields as NULL and quoted "" as empty strings, so the two sides disagree about the format. Remove the NULL '' option from the export so it uses the default, which writes NULL as an unquoted empty field and an empty string as "". Then both sides follow the same rule and the round trip preserves the difference.