Sub topic 1
What COPY Does and Why It Beats Row-by-Row INSERTs
PostgreSQL's COPY command moves many rows between a table and a data stream in one statement. The stream can be a file, a program, or the connection to your client. This chapter covers what COPY is, its general shape, and why it is the standard tool for bulk loading and exporting. Later chapters cover the CSV options, server-side file access, error handling, and tuning.
Prerequisites
This chapter assumes you have:
- Basic SQL:
CREATE TABLE,INSERT, andSELECT. - Some familiarity with the
psqlcommand-line client, including running a script with-fand typing commands at its prompt. - Knowledge of what a CSV file is: one record per line, fields separated by a delimiter, and an optional header line.
- A working idea of PostgreSQL data types such as
integer,text,numeric, anddate. - A PostgreSQL database where you can create tables. A scratch database is best.
The examples use this table throughout the tutorial:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);What COPY is
COPY is a PostgreSQL-specific command. It is not part of the SQL standard. It does one job: it transfers rows in bulk between a table (or a query result) and an external source or destination.
There are two directions:
COPY ... FROMreads rows from a source and appends them to a table.COPY ... TOwrites rows from a table or query to a destination.
The general shape is:
COPY table_name [ (column_list) ] FROM { 'filename' | PROGRAM 'command' | STDIN } [ WITH ( option [, ...] ) ]
COPY { table_name [ (column_list) ] | ( query ) } TO { 'filename' | PROGRAM 'command' | STDOUT } [ WITH ( option [, ...] ) ]The endpoint at the other end of the transfer can be one of four things:
| Endpoint | Meaning |
|---|---|
| `'filename'` | A file on the database server's filesystem |
| `PROGRAM 'command'` | A shell command run on the database server |
| `STDIN` | Data the client sends over the connection (for `FROM`) |
| `STDOUT` | Data the server sends back to the client (for `TO`) |
The STDIN and STDOUT forms are what psql's \copy command uses to read and write files on your own machine. The chapter on server-side COPY versus \copy covers that difference.
Data formats
COPY understands three formats, chosen with the FORMAT option:
text, the default: tab-separated columns, one row per line, with backslash escapes.csv: the comma-separated format with quoting rules that spreadsheets and most tools produce.binary: PostgreSQL's own compact format. It is fast but tied to PostgreSQL's type representations, so it is mainly useful between PostgreSQL databases.
This tutorial concentrates on csv. The next chapter describes its options.
A first, complete example
You can try COPY without any file. In psql, COPY ... FROM STDIN makes the server read data lines that follow the command, ending at a line containing only \.:
COPY products (id, name, price) FROM STDIN WITH (FORMAT csv);
1,Widget,9.99
2,Gadget,24.50
3,"Gizmo, large",31.00
\.psql prints the command tag:
COPY 3The tag reports how many rows were processed. Check the result:
SELECT id, name, price FROM products ORDER BY id;The third row shows that CSV quoting works as you would expect: the comma inside "Gizmo, large" stays part of the name.
The column list (id, name, price) names the table columns that receive the three fields on each line. The columns you leave out, released and notes, get their default values. Here the default is NULL.
Exporting is the mirror image. This sends the table to your terminal:
COPY products TO STDOUT WITH (FORMAT csv, HEADER true);Why row-by-row INSERTs are slow
Suppose an application loads 100,000 rows by sending one INSERT per row. Each statement pays several costs:
- A network round trip. The client sends the statement and waits for the server's reply before sending the next one. Even on a fast local network, 100,000 waits add up.
- Statement overhead. The server parses, analyzes, and plans each statement. For a one-row insert, this work can exceed the work of storing the row.
- A commit per row, in autocommit mode. Unless you open a transaction, each
INSERTis its own transaction. With the defaultsynchronous_commit = on, each commit waits for the write-ahead log (WAL) to be flushed to disk. This is often the largest cost. - Per-row storage work. Each row is placed into a table page and logged individually.
COPY removes most of these costs.
| Cost | One INSERT per row | COPY |
|---|---|---|
| Network round trips | One per statement | None per row; data streams |
| Parsing and planning | Once per statement | Once for the whole command |
| Transactions and WAL flushes | One per row in autocommit | One for the whole command |
| Storage | Row at a time | Rows are inserted in batches |
The diagram shows the difference in message flow.
Measuring it yourself
The following shell script is a rough benchmark. It generates 100,000 rows as individual INSERT statements and as a CSV file, then times each way of loading them. It assumes DATABASE_URL points at a scratch database that already contains the products table.
# Generate the same 100,000 rows in two forms.
seq 1 100000 | awk -v q="'" '{printf "INSERT INTO products (id, name, price) VALUES (%d, %sitem %d%s, %d.50);\n", $1, q, $1, q, $1 % 100}' > inserts.sql
seq 1 100000 | awk '{printf "%d,item %d,%d.50\n", $1, $1, $1 % 100}' > products.csv
# Row-by-row: psql runs each statement as its own transaction.
psql "$DATABASE_URL" -q -c "TRUNCATE products"
time psql "$DATABASE_URL" -q -f inserts.sql
# COPY: one command, one transaction.
psql "$DATABASE_URL" -q -c "TRUNCATE products"
time psql "$DATABASE_URL" -q -c "\copy products (id, name, price) FROM 'products.csv' WITH (FORMAT csv)"Exact timings depend on your hardware, your network, and settings such as synchronous_commit, so no number here applies to every system. The COPY run is typically many times faster than the autocommit run. Try the same comparison with the INSERT statements wrapped between BEGIN; and COMMIT;. That removes the per-row commit cost, and the gap shrinks. A single transaction around the inserts is the first optimization for any insert-heavy script, but COPY still has less per-row overhead.
What COPY does not skip
COPY is fast because it does less repeated work per row. It does not turn off the database's rules. For COPY FROM:
NOT NULL,CHECK, unique, primary key, and foreign key constraints are enforced.- Column defaults apply to any column not in the column list.
- Indexes are updated as rows are inserted.
- Row-level
BEFOREandAFTERinsert triggers fire. - Values are converted to the column type by that type's input function, so
'2026-11-27'becomes adateand'abc'fails for anintegercolumn. - The load is atomic. If any row fails, no rows from that command are kept. The chapter on errors covers this and the
ON_ERRORoption from PostgreSQL 17.
Because indexes and constraints still do their work, a very large load into a heavily indexed table is slower than one into a bare table. The performance chapter covers the standard techniques.
What COPY cannot do
Some limits shape how you design a load:
- No
ON CONFLICT. ACOPYinto a table with a duplicate primary key fails, and the whole command rolls back. To merge data into existing rows, load into a staging table and then useINSERT ... ON CONFLICT. That pattern has its own chapter. - No
RETURNING.COPYonly reports a row count. - No per-row transformation.
COPYcannot apply expressions to incoming values. It maps fields to columns and converts types, nothing more. Clean-up happens in SQL after loading. - Limited targets.
COPY FROMloads into plain tables, partitioned tables, and foreign tables. It also works on views that haveINSTEAD OF INSERTtriggers. It does not support tables with row-level security policies. - A table is only that table.
COPY products TO ...exports the rows stored inproductsitself, not rows in tables that inherit from it. To export a view, a join, or a filtered set, use the query formCOPY (SELECT ...) TO ....
When INSERT is still the right tool
COPY is for moving sets of rows, not for every write.
- Use
INSERTfor a handful of rows or for application code that writes one record at a time. - Use
INSERT ... RETURNINGwhen you need generated values such as identity columns back. - Use
INSERT ... ON CONFLICTfor a direct upsert. - Use
INSERT ... SELECTto copy rows between tables inside the database. No file or client transfer is involved, soCOPYoffers nothing there.
A reasonable rule of thumb is to reach for COPY once you are moving thousands of rows, or any time a file is the source or destination. For a few hundred rows the difference is hardly noticeable.
Common mistakes at this stage
Two other mistakes are common:
- Forgetting
HEADER true. When a CSV file has a header line and you do not say so,COPYtries to load the header as data. It then fails on the first non-text column, for example withinvalid input syntax for type integer: "id". - Mismatched column counts. If the file has a different number of fields than the target column list,
COPYfails with a message such asmissing data for column "price"orextra data after last expected column.
Exercise
A script loads 50,000 rows by running one INSERT statement per row through psql -f, with no BEGIN or COMMIT. List three separate costs that a single COPY command avoids, and say which of them is removed by wrapping the inserts in one transaction.
Show answer
A single COPY avoids (1) one network round trip per row, (2) parsing and planning of every statement, and (3) a transaction commit with a WAL flush for every row. Wrapping the inserts in BEGIN and COMMIT removes only the third cost, the per-row commit. The round trips and per-statement parsing remain, so COPY is still faster.
Exercise
You run COPY products (id, name, price) FROM STDIN WITH (FORMAT csv); in psql and send 100 valid lines, but line 80 repeats an id already in the table. How many rows are in the table afterward compared with before, and why? What would you use to merge such rows instead?
Show answer
The row count is unchanged. The unique violation on line 80 raises an error, and COPY is atomic, so all 100 rows from that command are rolled back. COPY has no ON CONFLICT clause. To merge rows, load into a staging table with COPY and then run INSERT ... SELECT ... ON CONFLICT from the staging table into products.
Exercise
Which form would you use to export only the products with a price above 10, and why can't you write it as COPY products TO ...?
Show answer
Use the query form, COPY (SELECT id, name, price FROM products WHERE price > 10) TO STDOUT WITH (FORMAT csv, HEADER true), or the same query with \copy to write a client-side file. COPY products TO ... takes no filter. It always exports every row stored in that table.