KlaroKit
← All posts

How to Map CSV Columns to a Postgres Table When the Names, Order and Types Don't Match

To map CSV columns to a Postgres table when the names, order and types don't match, don't load the file straight into the table. First load it with COPY (or psql's \copy) into a staging table where every column is text, so nothing can fail on the way in. Then run a query that lists the rows that won't convert to the right types, and fix them. Finally, move the rows across with one INSERT ... SELECT that names each target column and casts each value into its type.

What the file and the table look like

Say a sales team exports its customer list from a spreadsheet as customers_export.csv:

Cust Name,Signup Dt,Annual Rev ($),Cust ID,Email Addr,Active?
"Acme Hardware, Inc.",03/14/2023,"$12,500.00",1042,orders@acmehw.example,Y
Blue Fern Studio,11/02/2023,8400,1043,Hello@BlueFern.example,yes
Northgate Foods,31/01/2024,"$1,250,000",1044,,N
Harbor Lane Dental,06/09/2024,N/A,1045,office@harborlane.example,Y

It has to go into a customers table that already exists:

CREATE TABLE customers (
  customer_id     integer PRIMARY KEY,
  full_name       text NOT NULL,
  email           text,
  signed_up_on    date,
  annual_revenue  numeric(12,2),
  is_active       boolean NOT NULL DEFAULT true,
  loaded_at       timestamptz NOT NULL DEFAULT now()
);

Nothing lines up. The names differ, the ID is the fourth column instead of the first, the dates are US-style text, and the revenue has dollar signs and commas. Two rows also hide real problems: 31/01/2024 isn't a valid MM/DD/YYYY date, and N/A isn't a number.

Write the mapping down before any SQL

A small table like this keeps you from mapping in your head while you type. It also gives whoever runs the load next month something to check against. (If the term is new, here's what data mapping is, in plain English.)

CSV column Postgres column Rule
Cust ID customer_id Trim, cast to integer
Cust Name full_name Trim; required
Email Addr email Trim, lowercase, blank becomes NULL
Signup Dt signed_up_on Parse as MM/DD/YYYY
Annual Rev ($) annual_revenue Strip $, commas and spaces; blank becomes NULL; cast to numeric
Active? is_active Y/yes/N/no to boolean; blank becomes true
(none) loaded_at Not in the file; table default fills it

Most of these matches are obvious from the names. The rules are where the judgment goes, and they deserve a second pair of eyes. We wrote more about which column matches are safe to auto-map and which need a human check.

Step 1: Load the CSV into an all-text staging table

Create one text column per CSV column, in the file's order. COPY matches columns by position, not by header name. With HEADER true, it skips the first line without reading it, so you can name the staging columns whatever you like.

CREATE TABLE staging_customers (
  cust_name   text,
  signup_dt   text,
  annual_rev  text,
  cust_id     text,
  email_addr  text,
  active      text
);

Then load the file. \copy runs in psql and reads the file from your machine. Plain COPY ... FROM 'file' reads from the database server and needs extra privileges. Keep the \copy command on one line:

\copy staging_customers FROM 'customers_export.csv' WITH (FORMAT csv, HEADER true)

If the file uses semicolons instead of commas, add DELIMITER ';' to the options.

Because every column is text, every value lands exactly as written. The CSV format handles the quoted comma in "Acme Hardware, Inc.", and an empty unquoted field becomes NULL. Text also means nothing guesses a type on your behalf. A guessed type is how ZIP codes lose their leading zeros in CSV files, and you want to make that decision yourself.

Step 2: Find the rows that won't cast

One value that can't be cast makes the whole INSERT fail. That's safe, because nothing is half-loaded, but the error names only the first bad value it hit. This query lists every row that would fail, and which column is at fault:

SELECT *
FROM (
  SELECT cust_id, cust_name, signup_dt, annual_rev, active,
    concat_ws(', ',
      CASE WHEN coalesce(trim(cust_id), '') !~ '^[0-9]+$'
           THEN 'Cust ID' END,
      CASE WHEN coalesce(trim(cust_name), '') = ''
           THEN 'Cust Name' END,
      CASE WHEN trim(signup_dt) <> ''
            AND trim(signup_dt) !~ '^(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])/[0-9]{4}$'
           THEN 'Signup Dt' END,
      CASE WHEN regexp_replace(annual_rev, '[$,[:space:]]', '', 'g') <> ''
            AND regexp_replace(annual_rev, '[$,[:space:]]', '', 'g') !~ '^-?[0-9]+(\.[0-9]{1,2})?$'
           THEN 'Annual Rev ($)' END,
      CASE WHEN trim(active) <> ''
            AND lower(trim(active)) NOT IN ('y','yes','n','no','true','false','t','f','1','0')
           THEN 'Active?' END
    ) AS problems
  FROM staging_customers
) checked
WHERE problems <> '';

On the sample file it returns two rows: customer 1044 for Signup Dt and 1045 for Annual Rev ($). The date check catches impossible months and days above 31, but not a day that doesn't exist in its month, such as 02/30/2024. Give the dates it lets through a quick look for those.

Look twice at 1044 before you fix it. One DD/MM date suggests the export may mix formats. If it does, a row like 06/09/2024 could really mean September 6 and would load quietly as June 9. Ask whoever produced the file.

Fix the problems in staging and leave the original file untouched. Keep the fixes in your script so they're on record:

UPDATE staging_customers SET signup_dt  = '01/31/2024' WHERE cust_id = '1044';
UPDATE staging_customers SET annual_rev = NULL         WHERE cust_id = '1045';

Run the check again until it returns nothing.

Step 3: Rename, reorder and cast with one INSERT ... SELECT

The column list in the INSERT sets the target order. The SELECT gives one expression per target column, in that same order. Each expression is a row from the mapping table written as SQL.

BEGIN;

INSERT INTO customers
  (customer_id, full_name, email, signed_up_on, annual_revenue, is_active)
SELECT
  trim(cust_id)::integer,
  trim(cust_name),
  lower(nullif(trim(email_addr), '')),
  to_date(nullif(trim(signup_dt), ''), 'MM/DD/YYYY'),
  nullif(regexp_replace(annual_rev, '[$,[:space:]]', '', 'g'), '')::numeric(12,2),
  coalesce(nullif(trim(active), '')::boolean, true)
FROM staging_customers;

SELECT count(*) FROM staging_customers;

psql reports INSERT 0 4, and the count should say 4 too. If they match, run COMMIT; and then DROP TABLE staging_customers;. If they don't, run ROLLBACK; and nothing has changed.

The details that matter:

  • loaded_at isn't in the column list, so the table default fills it. A CSV column you don't need works the same way: it stays in staging and you leave it out of the SELECT.
  • A default only applies when the column is left out. Inserting an explicit NULL skips it. That's why is_active uses coalesce(..., true) instead of relying on DEFAULT true.
  • Postgres reads Y, yes, N and no as booleans on its own, in any case, so Active? needs no CASE.
  • Since Postgres 10, to_date raises an error on out-of-range values, such as a 31st month or a 40th day, instead of rolling them over into a different date. Before version 10, to_date('2009-06-40','YYYY-MM-DD') returned July 10, 2009.

Writing the mapping by hand is fine for six columns. When it's sixty, or the same export arrives every month with slightly different headers, that's the part we're building KlaroKit to help with. It's designed to suggest how the fields line up. A person approves each one, and nothing is applied without that approval. Every accepted mapping is remembered, so the next file starts closer to done. KlaroKit isn't out yet. If you'd like one email when early access opens, plus a launch discount, you can join the waitlist.

FAQ

What if some of these customers are already in the table?

A plain INSERT stops at the first duplicate customer_id and rolls everything back. Add ON CONFLICT (customer_id) DO NOTHING to skip existing customers. Use ON CONFLICT (customer_id) DO UPDATE SET email = EXCLUDED.email to overwrite only the columns you choose. DO UPDATE refuses to touch the same row twice in one statement, so check the file for repeated IDs first:

SELECT trim(cust_id), count(*)
FROM staging_customers
GROUP BY trim(cust_id)
HAVING count(*) > 1;

Why does COPY fail with "invalid byte sequence for encoding UTF8"?

The file isn't UTF-8. CSVs saved from Excel on Windows are often Windows-1252. Add ENCODING 'WIN1252' to the WITH (...) options so Postgres converts the file on the way in, or re-save the file as UTF-8 first.

Should the staging table be a temporary table?

CREATE TEMP TABLE works well when the \copy, the check and the INSERT all run in one psql session, such as a single script. The table disappears when you disconnect. If you want to inspect it later or from another session, use a regular or UNLOGGED table. UNLOGGED writes faster but is emptied after a crash, which is fine for data you can reload.

Can I skip the staging table and COPY straight into the target?

Yes, if the file already uses the target's formats. \copy customers (full_name, signed_up_on, ...) FROM ... lists the target columns in the file's order, which handles renaming and reordering. It can't strip a dollar sign or parse an unusual date, though, and one bad value stops the whole load. Postgres 17 added an ON_ERROR option to COPY that can skip rows with bad values, but skipped rows are easy to forget about. For a tidy one-off file, the direct route is plenty. For anything messier, staging first costs you the least time.