Sub topic 9
Staging Tables for Cleanup and Upserts
This chapter assumes basic SQL, familiarity with psql, and an existing products table with columns such as id, name, price, released, and notes. A staging table is a temporary or permanent table that receives imported data before the data reaches the real table.
Staging separates two jobs:
- Loading the file without changing production data.
- Checking, cleaning, and merging the loaded rows.
This approach is useful when the file contains duplicates, inconsistent values, or rows that need conversion.
Why use a staging table?
Loading directly into products makes validation harder. A failed conversion can stop the import, and an upsert can overwrite existing data before you inspect the input.
A staging table gives you a safe checkpoint:
For a clean file, make the staging table match the target:
CREATE TEMP TABLE products_stage (LIKE products);TEMP means that PostgreSQL removes the table automatically when your database session ends. The staging table is visible only in that session.
If the file may contain invalid values, use text columns for raw input. Text accepts values such as an empty price or a date written in an unexpected format. You can convert those values later:
CREATE TEMP TABLE products_stage_raw (
id text,
name text,
price text,
released text,
notes text
);Load and inspect the data
The following script keeps the staging table and the \copy command in one psql session. Replace products.csv with your file path.
psql "$DATABASE_URL" <<'SQL'
CREATE TEMP TABLE products_stage_raw (
id text,
name text,
price text,
released text,
notes text
);
\copy products_stage_raw (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true)
SELECT *
FROM products_stage_raw
WHERE NULLIF(trim(id), '') IS NULL
OR NULLIF(trim(name), '') IS NULL;
SQLThe query finds rows missing an identifier or name. You can run other checks before changing products.
| Check | Example condition | Possible action |
|---|---|---|
| Missing identifier | `NULLIF(trim(id), '') IS NULL` | Reject the row |
| Invalid price | `price !~ '^[0-9]+(\\.[0-9]{1,2})?$'` | Correct or reject it |
| Duplicate identifier | `GROUP BY id HAVING count(*) > 1` | Keep the newest row |
Clean and upsert the rows
An upsert inserts a row when its key is new and updates the existing row when the key already exists. PostgreSQL implements this with INSERT ... ON CONFLICT.
This example trims text, converts empty strings to NULL, and casts the cleaned values to their target types. The WHERE clause excludes rows that cannot safely become products.
INSERT INTO products (id, name, price, released, notes)
SELECT
trim(id)::integer,
trim(name),
NULLIF(trim(price), '')::numeric(10, 2),
NULLIF(trim(released), '')::date,
NULLIF(trim(notes), '')
FROM products_stage_raw
WHERE trim(id) ~ '^[0-9]+$'
AND NULLIF(trim(name), '') IS NOT NULL
AND (
NULLIF(trim(price), '') IS NULL
OR trim(price) ~ '^[0-9]+(\.[0-9]{1,2})?$'
)
AND (
NULLIF(trim(released), '') IS NULL
OR trim(released) ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'
)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price,
released = EXCLUDED.released,
notes = EXCLUDED.notes;EXCLUDED represents the row from the import that conflicted with an existing row. In this example, the imported values replace the old values.
If duplicate identifiers exist in the staging table, one insert statement can attempt to affect the same target row more than once. PostgreSQL rejects that command. Remove or rank duplicates first.
DELETE FROM products_stage_raw a
USING products_stage_raw b
WHERE a.id = b.id
AND a.ctid < b.ctid;ctid identifies a physical row version, so this is suitable for a short-lived staging table, not as a permanent identifier. It keeps one arbitrary row for each duplicate identifier. For predictable results, add an import timestamp or source-row number and choose the desired row with row_number().
Exercise
Why might a raw staging table use text columns instead of the target table's numeric and date types?
Show answer
Text columns allow the file to load even when values need cleanup. The import query can then validate and convert acceptable values before inserting them into the target table.