Skip to main content

Databases · Beginner · 20 min

Load and export CSV data with PostgreSQL COPY

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7

You will load a messy 200,000-row CSV of transport fares into PostgreSQL 18 through a staging table, skip bad rows with ON_ERROR ignore, time COPY against row-by-row INSERTs and export a summary back to CSV.

On this page

Most data arrives as a CSV file: an export from a ticketing system, a spreadsheet from a partner, a dump from another database. PostgreSQL's COPY command reads and writes CSV directly, and it is far faster than sending one INSERT per row. It is also strict. One impossible date stops the whole load, and COPY reports only the first bad row, so you find and fix problems one at a time.

In this tutorial you generate a deliberately messy CSV of 200,000 bus and minibus fares across Lagos, Nairobi, Accra and Dakar. You load it with psql's \copy, see why the server-side COPY refuses the same file, land everything in an all-text staging table, and move the good rows into a typed table while keeping a list of the bad ones and the reason for each. You then try ON_ERROR ignore as the one-command alternative, load a semicolon-separated partner file, time COPY against row-by-row INSERTs, and export results back to CSV.

The commands use PostgreSQL 18. They should work unchanged on PostgreSQL 19, released in November 2026, but they were only run against 18. ON_ERROR needs PostgreSQL 17 or later, and REJECT_LIMIT needs 18.

Step 1 · Create a role, a database and a working folder

Work in a throwaway folder and give yourself a PostgreSQL role with the same name as your Linux user. On Ubuntu the local socket uses peer authentication, so that role lets you run psql without sudo and without a password. Then create a database called fares that you own.

Bash
mkdir -p ~/fares-demo
cd ~/fares-demo
sudo -u postgres createuser "$USER"
sudo -u postgres createdb -O "$USER" fares

If createuser says the role already exists, you made one in an earlier tutorial, and that is fine. Your role is not a superuser, which matters in step 3.

Run every command from here on inside ~/fares-demo, because \copy reads and writes file names relative to the folder you are in.

Check it worked

Bash
psql -d fares -Atc "SELECT current_user, current_database();"

The output is your Linux user name and fares, separated by a |.

Step 2 · Generate a messy fares file

Real exports are messy in predictable ways, and this generator builds those problems in on purpose so that every count later in the tutorial is the same for you as it is here. Save it as make-fares.awk:

Bash
cat > make-fares.awk <<'AWK'
BEGIN {
  route[0] = "Ojota - CMS";                 op[0] = "BRT";    cur[0] = "NGN"; base[0] = 500
  route[1] = "\"Ikeja, Allen - Obalende\""; op[1] = "Danfo";  cur[1] = "NGN"; base[1] = 400
  route[2] = "\"Mile 12 \"\"Express\"\" - Ketu\""; op[2] = "Danfo"; cur[2] = "NGN"; base[2] = 300
  route[3] = "Kencom - Westlands";          op[3] = "Matatu"; cur[3] = "KES"; base[3] = 80
  route[4] = "Circle - Madina";             op[4] = "Trotro"; cur[4] = "GHS"; base[4] = 12
  route[5] = "Médina - Plateau";            op[5] = "Bus";    cur[5] = "XOF"; base[5] = 250

  print "trip_id,route,operator,travelled_on,fare,currency,passengers,notes"
  for (i = 1; i <= 200000; i++) {
    r = i % 6
    day = sprintf("2026-%02d-%02d", i % 12 + 1, i % 28 + 1)
    if (i % 1000 == 0) day = "2026-02-30"
    fare = sprintf("%d.%02d", base[r] + (i % 7) * 10, (i % 4) * 25)
    if (i % 5000 == 2500) fare = "free"
    else if (i % 97 == 0) fare = ""
    pax = i % 4 + 1
    if (i % 333 == 0) pax = ""
    notes = ""
    if (i % 10 == 3) notes = "\"\""
    if (i % 50000 == 1) notes = "\"Late bus\nRefund issued\""
    printf "%d,%s,%s,%s,%s,%s,%s,%s\n", i, route[r], op[r], day, fare, cur[r], pax, notes
  }
}
AWK
awk -f make-fares.awk > fares.csv

What the file contains:

  • A header line naming the eight columns.
  • Route names with a comma ("Ikeja, Allen - Obalende") and with double quotes inside ("Mile 12 ""Express"" - Ketu"). CSV wraps such a field in quotes and doubles any quote inside it.
  • One accented name, Médina - Plateau, written as UTF-8.
  • Every 1,000th trip has the impossible date 2026-02-30, and 40 trips have the fare free. These are the bad rows.
  • Some fares and passenger counts are blank, meaning unknown.
  • Most notes are blank, every tenth note is "" (a quoted empty string), and four notes contain a line break inside quotes.

Check it worked

Bash
wc -l fares.csv
head -n 5 fares.csv

wc -l reports 200005 lines: the header, 200,000 trips, and 4 extra lines from the notes that contain a line break. That is why you should never count CSV rows with wc -l. The first trip spans two lines in the head output for the same reason. The file is about 11 MB.

Step 3 · Load the file with \copy into a staging table

Create a staging table where every column is text. Text accepts anything, so the load cannot fail on a bad value, and you deal with types in the next step where you can see the problems.

Bash
psql -d fares -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE fares_staging (
  trip_id      text,
  route        text,
  operator     text,
  travelled_on text,
  fare         text,
  currency     text,
  passengers   text,
  notes        text
);
SQL

PostgreSQL has two ways to load a file, and the difference is who reads it.

  • COPY table FROM '/path/file.csv' is SQL. The database server opens the file, as the postgres operating-system user, on the server's own disk. Only superusers and roles granted pg_read_server_files may do it, because that role can read any file the server can.
  • \copy table FROM 'file.csv' is a psql command. psql opens the file as you, on the machine where psql runs, and streams it to the server. Any role that can insert into the table can use it.

Try the server-side form first, as your own role:

Bash
psql -d fares -c "COPY fares_staging FROM '$HOME/fares-demo/fares.csv' WITH (FORMAT csv, HEADER true);"

It fails with an error like this:

Text
ERROR:  permission denied to COPY from a file
DETAIL:  Only roles with privileges of the "pg_read_server_files" role may COPY from a file.
HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.

Even as the postgres superuser it would fail here with Permission denied, because the server process cannot read inside your home folder. Server-side COPY is for files that already sit on the database server in a folder the postgres user can read. For a file on your machine, use \copy:

Bash
psql -d fares -c "\copy fares_staging FROM 'fares.csv' WITH (FORMAT csv, HEADER true)"

The options do three jobs. FORMAT csv turns on CSV quoting rules, so commas and line breaks inside quotes stay part of the field. HEADER true skips the first line. In CSV format an unquoted empty field becomes NULL, while a quoted empty field ("") becomes an empty string. Unlike most psql commands, \copy takes the whole rest of the line as its arguments, so it must fit on one line and does not end with a semicolon.

Check it worked

psql prints COPY 200000. Look at how the empty fields landed:

Bash
psql -d fares -c "SELECT count(*) AS rows, count(*) FILTER (WHERE notes IS NULL) AS null_notes, count(*) FILTER (WHERE notes = '') AS empty_notes, count(DISTINCT route) AS routes FROM fares_staging;"

You see 200,000 rows, 179,996 null notes, 20,000 empty-string notes and 6 routes. If routes shows more than 6, the file was loaded without FORMAT csv and the commas inside quotes split the route names.

Step 4 · Cast into a typed table and keep the rejects

Create the table you want to keep, with real types:

Bash
psql -d fares -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE fares (
  trip_id      bigint PRIMARY KEY,
  route        text NOT NULL,
  operator     text NOT NULL,
  travelled_on date NOT NULL,
  fare         numeric(10,2),
  currency     char(3) NOT NULL,
  passengers   integer,
  notes        text
);
SQL

The obvious next move is one INSERT ... SELECT that casts every column:

Bash
psql -d fares -c "INSERT INTO fares SELECT trip_id::bigint, route, operator, travelled_on::date, fare::numeric(10,2), currency, passengers::integer, notes FROM fares_staging;"

It stops with something like ERROR: date/time field value out of range: "2026-02-30" and inserts nothing. The message names the value but not the row, and fixing one problem only shows you the next.

Instead, find every bad row first. pg_input_is_valid(value, type) tests whether a string would cast without raising an error, and pg_input_error_info(value, type) returns the error message it would raise. Both arrived in PostgreSQL 16. Put the failures in their own table with a reason:

Bash
psql -d fares -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE fares_rejected AS
SELECT s.*,
       coalesce((pg_input_error_info(s.travelled_on, 'date')).message,
                (pg_input_error_info(s.fare, 'numeric(10,2)')).message) AS reason
FROM fares_staging AS s
WHERE NOT pg_input_is_valid(s.travelled_on, 'date')
   OR NOT pg_input_is_valid(s.fare, 'numeric(10,2)');

SELECT reason, count(*) FROM fares_rejected GROUP BY reason ORDER BY count(*) DESC;
SQL

The summary has two lines: 200 rows with a date error that quotes 2026-02-30, and 40 rows with invalid input syntax for type numeric: "free". Both functions return NULL for a NULL input, so blank fares are not counted as bad. In your own data, add a test for every column you cast.

Now insert everything that is not in the reject table:

Bash
psql -d fares -v ON_ERROR_STOP=1 <<'SQL'
INSERT INTO fares
SELECT trip_id::bigint, route, operator, travelled_on::date,
       fare::numeric(10,2), currency, passengers::integer, notes
FROM fares_staging AS s
WHERE NOT EXISTS (SELECT 1 FROM fares_rejected AS r WHERE r.trip_id = s.trip_id);
SQL

Check it worked

psql prints INSERT 0 199760. That is 200,000 minus the 240 rejects, and fares_rejected still holds each bad row exactly as it arrived, ready to send back to whoever produced the file.

Bash
psql -d fares -c "SELECT count(*) AS kept, count(*) FILTER (WHERE fare IS NULL) AS unknown_fare, count(*) FILTER (WHERE passengers IS NULL) AS unknown_passengers FROM fares;"

You see 199,760 kept rows, 2,059 with an unknown fare and 600 with an unknown passenger count.

Step 5 · Skip bad rows in one command with ON_ERROR ignore

Since PostgreSQL 17, COPY can skip rows whose values do not convert to the column type, instead of stopping. Load the file straight into a second typed table with the same definition:

Bash
psql -d fares -c "CREATE TABLE fares_direct (LIKE fares INCLUDING ALL);"
psql -d fares -c "\copy fares_direct FROM 'fares.csv' WITH (FORMAT csv, HEADER true, ON_ERROR ignore)"

psql prints a notice like NOTICE: 240 rows were skipped due to data type incompatibility, then COPY 199760. The notice is the only record of what was skipped. To see which rows they were, add LOG_VERBOSITY verbose, which prints one notice per skipped row with its line number, column and value. Try it on the first 1,000 trips, read through head with \copy ... FROM PROGRAM (psql runs the program as you):

Bash
psql -d fares -c "CREATE TABLE fares_sample (LIKE fares INCLUDING ALL);"
psql -d fares -c "\copy fares_sample FROM PROGRAM 'head -n 1002 fares.csv' WITH (FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose)"

You see a notice like skipping row due to data type incompatibility at line 1002 for column "travelled_on": "2026-02-30", a count of 1 skipped row and COPY 999. The line number counts physical lines in the file, including the line break inside the first trip's quoted note, the same way wc -l does, so it is the line you jump to in an editor rather than the trip number. On 200,000 rows that would be 240 notices, which is why the staging table is the better tool when you need to hand the rejects back.

ON_ERROR ignore has limits worth knowing before you rely on it:

  • It only covers type conversion. A row with the wrong number of columns, a duplicate primary key or a NOT NULL violation still stops the load.
  • Without a limit it skips everything that fails. If a supplier changes the date format, every row is skipped and the load still "succeeds" with zero rows.

PostgreSQL 18 adds REJECT_LIMIT for the second problem. This load allows at most 100 bad rows:

Bash
psql -d fares -c "CREATE TABLE fares_strict (LIKE fares INCLUDING ALL);"
psql -d fares -c "\copy fares_strict FROM 'fares.csv' WITH (FORMAT csv, HEADER true, ON_ERROR ignore, REJECT_LIMIT 100)"

It fails with an error that it skipped more than REJECT_LIMIT (100) rows. Like any failed COPY, it rolls back, so fares_strict stays empty rather than half loaded.

Check it worked

Bash
psql -d fares -Atc "SELECT (SELECT count(*) FROM fares_direct) = (SELECT count(*) FROM fares);"

The answer is t: one command gave the same 199,760 rows as the staging route, without the list of rejects.

Step 6 · Load a semicolon file with its own NULL marker

Spreadsheets set to French or Portuguese, common across francophone and lusophone Africa, save "CSV" with semicolons between fields and a comma as the decimal mark, because the comma is already taken. A partner operator in Dakar sends this file, which writes unknown values as NA:

Bash
cat > partner.csv <<'CSV'
trip_id;route;operator;travelled_on;fare;currency;passengers;notes
900001;Médina - Plateau;Bus;2026-11-02;250,00;XOF;2;NA
900002;Médina - Plateau;Bus;2026-11-02;NA;XOF;1;Carte perdue
900003;Plateau - Yoff;Bus;2026-11-03;300,00;XOF;NA;NA
900004;Plateau - Yoff;Bus;2026-11-03;300,00;XOF;3;"Retard; pluie"
CSV

Load it into its own staging table. DELIMITER ';' sets the separator, NULL 'NA' makes the unquoted text NA mean NULL, and HEADER match checks that the header names equal the table's column names, so a supplier who reorders columns gets an error instead of a silent mix-up:

Bash
psql -d fares -c "CREATE TABLE partner_staging (LIKE fares_staging);"
psql -d fares -c "\copy partner_staging FROM 'partner.csv' WITH (FORMAT csv, DELIMITER ';', NULL 'NA', HEADER match)"
psql -d fares -P null='(null)' -c "SELECT trip_id, fare, passengers, notes FROM partner_staging ORDER BY trip_id;"

The quoted "Retard; pluie" stays one field even though it contains the delimiter. Now swap the decimal comma for a point as you cast, and add the rows to fares:

Bash
psql -d fares -v ON_ERROR_STOP=1 <<'SQL'
INSERT INTO fares
SELECT trip_id::bigint, route, operator, travelled_on::date,
       replace(fare, ',', '.')::numeric(10,2), currency, passengers::integer, notes
FROM partner_staging;
SQL

If a file comes from older Windows software and accents turn into odd symbols, it is probably not UTF-8. Add ENCODING 'WIN1252' (or the file's real encoding) to the \copy options and PostgreSQL converts it as it loads.

Check it worked

The SELECT showed (null) for trip 900002's fare, trip 900003's passengers and two of the notes, and the insert printed INSERT 0 4.

Bash
psql -d fares -c "SELECT trip_id, fare, passengers FROM fares WHERE trip_id > 900000 ORDER BY trip_id;"

The fares read 250.00, empty, 300.00 and 300.00.

Step 7 · Time COPY against row-by-row INSERTs

Many import scripts loop over a file and send one INSERT per row. To see what that costs, write the first 20,000 fares out as INSERT statements. format() with %L quotes each value as an SQL literal and writes NULL for nulls:

Bash
psql -d fares -c "CREATE TABLE fares_speed (LIKE fares);"
psql -d fares -Atc "SELECT format('INSERT INTO fares_speed VALUES (%L, %L, %L, %L, %L, %L, %L, %L);', trip_id, route, operator, travelled_on, fare, currency, passengers, notes) FROM fares ORDER BY trip_id LIMIT 20000" > inserts.sql
psql -d fares -c "\copy (SELECT * FROM fares ORDER BY trip_id LIMIT 20000) TO 'speed.csv' WITH (FORMAT csv)"

Now load the same 20,000 rows three ways, emptying the table in between. First, one transaction per INSERT, which is what a script with autocommit on does:

Bash
time psql -q -d fares -f inserts.sql
psql -d fares -c "TRUNCATE fares_speed;"

Second, the same statements in a single transaction (-1):

Bash
time psql -q -d fares -1 -f inserts.sql
psql -d fares -c "TRUNCATE fares_speed;"

Third, \copy from CSV:

Bash
time psql -d fares -c "\copy fares_speed FROM 'speed.csv' WITH (FORMAT csv)"

The exact times depend on your disk and CPU, but the order does not change. The autocommit run is slowest by far, because every commit waits for the write-ahead log to reach the disk. One transaction removes those waits but still parses and plans 20,000 statements. COPY sends one command and a stream of rows, and is usually several times faster again. On a small cloud server expect seconds for the first run and a fraction of a second for COPY.

Check it worked

Bash
psql -d fares -Atc "SELECT count(*) FROM fares_speed;"

The answer is 20000, from the COPY run.

Step 8 · Export query results back to CSV

\copy also writes. Give it a query in brackets and a file name, and it writes the result as you, on your machine. Because \copy must fit on one line, longer queries read better as SQL COPY ... TO STDOUT followed by psql's \g file, which sends the output to a file and can span many lines:

Bash
psql -d fares -q <<'SQL'
COPY (
  SELECT operator, route, currency,
         count(*) AS trips,
         round(avg(fare), 2) AS avg_fare
  FROM fares
  GROUP BY operator, route, currency
  ORDER BY operator, route
) TO STDOUT WITH (FORMAT csv, HEADER true)
\g route-summary.csv
SQL
cat route-summary.csv

COPY ... TO STDOUT needs no special role, since the server only streams rows back to psql, which writes the file. The output:

Text
operator,route,currency,trips,avg_fare
BRT,Ojota - CMS,NGN,33254,530.25
Bus,Médina - Plateau,XOF,33335,280.50
Bus,Plateau - Yoff,XOF,2,300.00
Danfo,"Ikeja, Allen - Obalende",NGN,33334,430.50
Danfo,"Mile 12 ""Express"" - Ketu",NGN,33254,330.25
Matatu,Kencom - Westlands,KES,33333,110.50
Trotro,Circle - Madina,GHS,33252,42.25

COPY quoted the two route names that need it and left the rest bare. avg ignores the null fares, which is why trip 900002 counts as a trip but does not pull the Médina average down.

For a full export you will send over a slow or metered connection, such as prepaid mobile data, compress it as you write. \copy ... TO PROGRAM pipes the CSV into a command that psql runs as you:

Bash
psql -d fares -c "\copy fares TO PROGRAM 'gzip > fares-clean.csv.gz' WITH (FORMAT csv, HEADER true)"
ls -lh fares.csv fares-clean.csv.gz

Check it worked

route-summary.csv has a header and seven rows matching the output above, and fares-clean.csv.gz is a fraction of the size of the 11 MB original. Count its rows by loading it back into a scratch table:

Bash
psql -d fares -c "CREATE TABLE fares_roundtrip (LIKE fares INCLUDING ALL);"
psql -d fares -c "\copy fares_roundtrip FROM PROGRAM 'gzip -dc fares-clean.csv.gz' WITH (FORMAT csv, HEADER true)"

psql prints COPY 199764, the same number of rows as fares.

Step 9 · Clean up

The next commands delete the fares database and the demo folder. Leave them if you want to keep practising first.

Bash
cd ~
dropdb fares
rm -rf ~/fares-demo

The next command deletes the PostgreSQL role named after your Linux user. Run it only if you created that role in the first step and nothing else uses it.

Bash
sudo -u postgres dropuser "$USER"

Check it worked

Bash
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_database WHERE datname = 'fares';"

The answer is 0, and ls ~/fares-demo reports that the folder does not exist.

Next steps

  • Clean the file before it reaches the database when the problems are text, not types: /tutorials/clean-a-csv-file-with-pandas.
  • Learn more of psql's backslash commands, including \g, \o and scripts that stop at the first error: /tutorials/get-around-postgresql-with-psql-meta-commands.
  • Turn the loaded fares into answers with grouped totals: /tutorials/summarise-data-with-group-by-and-having.
  • Before loading into a database that matters, take a backup you can restore: /tutorials/back-up-and-restore-postgresql-with-pg-dump.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.