Sub topic 9
Staging Tables for Cleanup and Upserts
This chapter assumes you can write CREATE TABLE, INSERT, and SELECT, that you use psql, and that you have read the earlier chapters on COPY FROM, \copy, and column lists. The examples use the products table from the start of the tutorial.
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);Why load into a staging table first
COPY FROM writes rows straight into its target table. It checks types, NOT NULL, and constraints as it goes. If one row violates a rule, the whole command fails (see the chapter on errors and ON_ERROR). COPY also has no "update if exists" behavior. If a row's id already exists in products, the primary key rejects it and the load aborts.
Real files cause both problems. They contain duplicate keys, padded whitespace, blank names, and rows that repeat data you already hold. A staging table separates the work into steps:
- Load the raw file into a scratch table that has no constraints.
- Inspect and clean the data with ordinary SQL.
- Merge the cleaned rows into the real table.
Each step is a normal SQL statement, so you can run it, check the result, and fix it before anything touches production data.
Creating the staging table
The simplest way to create a staging table is LIKE.
CREATE TEMP TABLE products_stage (LIKE products);Three details matter here.
TEMPmakes the table private to your session. PostgreSQL drops it when the session ends. Other sessions cannot see it, so two people can use the same name without conflict.LIKE productscopies column names, types, andNOT NULLconstraints. It does not copy the primary key, defaults, or indexes unless you addINCLUDING ALL. Without a primary key, the staging table accepts duplicateidvalues, which is useful because you want to see the duplicates.- Because
NOT NULLis copied, a row with an emptynamestill fails during theCOPYinto the staging table. That defeats the purpose if you want to clean such rows with SQL.
For a dirty file, create a looser table. Declaring every column as text means that no value can fail conversion during the COPY. You then convert types in SQL, where you control what happens to bad values.
CREATE TEMP TABLE products_raw (
id text,
name text,
price text,
released text,
notes text
);Choose between the two designs by how dirty the file is.
| Design | Use when | Cost |
|---|---|---|
| `LIKE products` | The file is mostly clean and you mainly need duplicate handling and upserts | A type or `NOT NULL` error still aborts the load |
| All-`text` columns | The file may contain bad dates, bad numbers, or blanks | You must cast each column yourself |
Loading the file
Load with \copy so that the file can live on your machine. The ON COMMIT behavior of temporary tables does not matter here, because psql runs each statement in its own transaction by default and temporary tables persist until the session ends.
CREATE TEMP TABLE products_stage (LIKE products);
\copy products_stage FROM 'products.csv' WITH (FORMAT csv, HEADER true)Check what arrived before you change anything.
SELECT count(*) FROM products_stage;
SELECT * FROM products_stage ORDER BY id LIMIT 10;Cleaning the data
Cleanup is ordinary SQL against the staging table. A few typical steps:
-- Trim stray whitespace
UPDATE products_stage
SET name = btrim(name);
-- Turn empty notes into NULL
UPDATE products_stage
SET notes = NULL
WHERE notes = '';
-- Find duplicate keys inside the file
SELECT id, count(*)
FROM products_stage
GROUP BY id
HAVING count(*) > 1;Duplicates inside the file deserve special attention. They cause a specific upsert failure, covered below. Decide which copy of a duplicated key to keep, then delete the others. If the file has no ordering column, you can use the physical row identifier ctid to pick one arbitrarily.
DELETE FROM products_stage a
USING products_stage b
WHERE a.id = b.id
AND a.ctid < b.ctid;This keeps the row that sits last in the table and removes earlier ones. For a freshly loaded staging table, that matches the file order, so the last occurrence in the file wins. Do not rely on ctid after updates, because an UPDATE moves rows to new physical locations. Run the deduplication before other updates, or use a real sequence column that you add to the staging table.
If you loaded into the all-text table, convert while you insert into a typed table or a typed query. Casting a bad value raises an error, so filter first.
SELECT id::integer,
btrim(name) AS name,
price::numeric(10,2),
released::date,
NULLIF(notes, '') AS notes
FROM products_raw
WHERE id ~ '^\d+$'
AND btrim(name) <> ''
AND price ~ '^\d+(\.\d+)?$'
AND released ~ '^\d{4}-\d{2}-\d{2}$';The regular-expression filters keep unusable rows out of the cast. A date such as 2026-02-31 matches the pattern but is not a real date, and the cast will still fail. For strict validation, rows can be checked in a function that catches the conversion error. For most files, a pattern filter plus a look at the rejected rows is enough. See the next section for how to list them.
Reviewing rejected rows
Do not silently drop rows. Query the complement of your filter to see what you are discarding.
SELECT *
FROM products_raw
WHERE NOT (
id ~ '^\d+$'
AND btrim(name) <> ''
);Save these rows with \copy ... TO so that the data owner can correct them. This is a real advantage over ON_ERROR ignore, which skips bad rows without keeping them.
Merging with INSERT ... ON CONFLICT
With clean data in products_stage, merge it into products.
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;How it works:
INSERT ... SELECTreads every staging row.SELECT *relies on the staging table having the same column order asproducts. WithLIKEthat is true. Name the columns explicitly when you are not sure.ON CONFLICT (id)names the unique index that detects a clash. Here it is the primary key.DO UPDATEruns when a row with thatidalready exists.EXCLUDEDis a pseudo-table holding the row that would have been inserted.- New ids are inserted. Existing ids are overwritten with the file's values.
The duplicate-within-the-batch error
If two staging rows have the same id and both would hit DO UPDATE, PostgreSQL stops with this error:
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.The command cannot decide which of the two rows should win. The fix is the deduplication step shown earlier, or SELECT DISTINCT ON (id) in the merge query:
INSERT INTO products (id, name, price, released, notes)
SELECT DISTINCT ON (id) id, name, price, released, notes
FROM products_stage
ORDER BY id, released DESC NULLS LAST
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price,
released = EXCLUDED.released,
notes = EXCLUDED.notes;DISTINCT ON (id) keeps the first row for each id according to the ORDER BY. Here that is the row with the latest released date.
Updating only what changed
The plain upsert rewrites every matching row, even if nothing changed. Each rewrite creates a new row version, which adds table bloat and write-ahead log volume. Add a WHERE clause to skip identical rows.
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
WHERE (products.name, products.price, products.released, products.notes)
IS DISTINCT FROM
(EXCLUDED.name, EXCLUDED.price, EXCLUDED.released, EXCLUDED.notes);IS DISTINCT FROM treats two NULL values as equal, which a plain <> does not. Without it, rows with a NULL price would always look changed.
Insert-only merges
To add new products and leave existing ones alone, use DO NOTHING.
INSERT INTO products
SELECT * FROM products_stage
ON CONFLICT (id) DO NOTHING;Keeping the merge atomic
Each of the cleanup and merge statements is its own transaction in psql. If you want the merge to be all-or-nothing together with cleanup steps, wrap them in one transaction. A temporary table can be used inside a transaction like any other table.
BEGIN;
CREATE TEMP TABLE products_stage (LIKE products) ON COMMIT DROP;
\copy products_stage FROM 'products.csv' WITH (FORMAT csv, HEADER true)
UPDATE products_stage SET name = btrim(name);
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;
COMMIT;ON COMMIT DROP removes the staging table when the transaction ends, so a script can run again without a "relation already exists" error. If any statement fails, psql leaves the transaction in an aborted state. Everything is rolled back when you issue ROLLBACK or the session ends, and products is unchanged.
Edge cases and gotchas
- Staging table has no primary key. That is intentional, but it means a repeated key in the file is not caught until the merge. Check for duplicates before merging.
- Column order.
INSERT INTO products SELECT * ...breaks quietly if someone adds a column toproductslater. Production scripts should list columns on both sides. - Deleted rows. An upsert never removes rows. If the file is a full snapshot and rows missing from it should be deleted, you need a separate
DELETE FROM products WHERE id NOT IN (SELECT id FROM products_stage). Run it only when you are sure the file is complete, because a truncated file would delete real data. - Large staging tables. A temporary table has no autovacuum processing and no statistics until analyzed. For a big file, run
ANALYZE products_stage;before the merge so the planner makes good choices. - Concurrent writers.
ON CONFLICTis safe against other sessions inserting the same key at the same time. The staging approach does not lockproductswhile you clean, so other sessions can change it in the meantime. The merge sees their changes and updates accordingly.
Summary
Load raw data into a temporary table, inspect and clean it with SQL, then merge it with INSERT ... ON CONFLICT. Use all-text columns when the file is untrustworthy. Remove duplicate keys before the merge. Add an IS DISTINCT FROM filter to avoid pointless updates, and wrap the whole job in one transaction when it must be all-or-nothing.
Exercise
A staging table named productsstage contains two rows with id 7. You run INSERT INTO products SELECT * FROM productsstage ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, and product 7 already exists in products. What happens, and how do you fix it so the row with the latest released date wins?
Show answer
The command fails with "ON CONFLICT DO UPDATE command cannot affect row a second time", because two proposed rows would update the same existing row. Fix it by choosing one row per id in the SELECT, for example SELECT DISTINCT ON (id) id, name, price, released, notes FROM products_stage ORDER BY id, released DESC NULLS LAST, or by deleting the unwanted duplicates from the staging table before the merge.
Exercise
Why might you create the staging table with every column typed as text instead of using LIKE products, and what must you do afterwards?
Show answer
With text columns, COPY cannot fail on a bad number, a bad date, or an empty value in a NOT NULL column, so the whole file loads and you can inspect the problem rows with SQL. Afterwards you must cast each column to its real type yourself (for example price::numeric(10,2) and released::date), filtering out or fixing rows that would fail the cast before you merge into products.