Importing and exporting data
Overview
Data rarely starts life in your database. It arrives as CSV exports from spreadsheets, files from suppliers, dumps from other systems. And it often needs to leave again — for a spreadsheet, a BI tool or a colleague. PostgreSQL’s COPY command moves data between tables and files in bulk, and psql’s \copy wraps it so you can use files on your own computer.
The examples in this lesson read and write files, so their output was captured by running them with psql against a PostgreSQL server; the CSV files used are shown inline.
COPY and \copy
There are two flavours with the same options:
COPYis an SQL command executed by the server.COPY products FROM '/data/products.csv'reads a file on the database server’s disk, which requires special privileges — and on a cloud database you can’t put files there at all.\copyis a psql command. It reads or writes the file on your computer and streams the data to the server. This is almost always what you want.
\copy is a psql meta-command, so it must fit on one line and doesn’t end with a semicolon. Graphical tools have import/export wizards that do the same job, and every database driver exposes COPY for programs.
Importing a CSV file
Here’s a supplier’s file, new_products.csv:
name,category,price,stock
Oolong Reserve,Tea,16.50,20
Cold Brew Kit,Equipment,34.00,8
Milk Frother,Accessories,19.99,15The file names categories, not ids, so it can’t go straight into products. The professional pattern is to load it into a staging table whose columns match the file, then move it into the real table with SQL:
CREATE TABLE product_import (
name text,
category text,
price numeric(10,2),
stock integer
);CREATE TABLE\copy product_import FROM 'new_products.csv' WITH (FORMAT csv, HEADER)COPY 3FORMAT csv understands quoting ("Kettle, 1.7 litre") and treats empty unquoted fields as NULL; HEADER skips the first line. Other options include DELIMITER ';' for semicolon-separated files (common in European spreadsheets) and ENCODING 'LATIN1' for files that aren’t UTF-8. You can also list the columns being filled: \copy product_import (name, price) FROM ….
SELECT * FROM product_import; name | category | price | stock
----------------+-------------+-------+-------
Oolong Reserve | Tea | 16.50 | 20
Cold Brew Kit | Equipment | 34.00 | 8
Milk Frother | Accessories | 19.99 | 15
(3 rows)Now move it into products, looking up each category id by name — an INSERT … SELECT with a join:
INSERT INTO products (name, category_id, price, stock)
SELECT i.name, c.id, i.price, i.stock
FROM product_import AS i
LEFT JOIN categories AS c ON c.name = i.category
RETURNING id, name, category_id, price; id | name | category_id | price
----+----------------+-------------+-------
13 | Oolong Reserve | 2 | 16.50
14 | Cold Brew Kit | 3 | 34.00
15 | Milk Frother | 4 | 19.99
(3 rows)
INSERT 0 3The Accessories category finally has a product. The LEFT JOIN means a row with an unknown category still loads, with a NULL category, rather than vanishing — you could equally use an inner join and report the rejects separately.
Why a staging table? Because you get the full power of SQL between the file and your real data: trim spaces, fix capitalisation, look up ids, skip duplicates with ON CONFLICT, and check everything with SELECT before it touches the real table.
When rows are bad
Every row is checked as it’s loaded. A value that doesn’t fit the column’s type stops the COPY, and the error tells you exactly where:
name,category,price,stock
Rooibos,Tea,twelve,10\copy product_import FROM 'typo_products.csv' WITH (FORMAT csv, HEADER)ERROR: invalid input syntax for type numeric: "twelve"
CONTEXT: COPY product_import, line 2, column price: "twelve"Like any statement, COPY is all-or-nothing: if line 50,000 of a 100,000-line file is bad, none of it is loaded. PostgreSQL 17 and later can skip rows with type errors instead, with WITH (FORMAT csv, HEADER, ON_ERROR ignore), and report how many were skipped — handy for messy files, as long as you check what was dropped.
Constraints on the real table are checked when you move the rows across. A staging table with relaxed types (everything text, no constraints) accepts anything, and you then find problems with ordinary queries, such as SELECT * FROM product_import WHERE price !~ '^[0-9.]+$'.
Exporting query results
\copy works in the other direction too, and it can export the result of any query — wrap the query in brackets:
\copy (SELECT o.id, c.first_name, c.country, o.ordered_at::date AS day, o.status FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE o.status IN ('paid', 'pending') ORDER BY o.id) TO 'open_orders.csv' WITH (FORMAT csv, HEADER)COPY 4The file open_orders.csv now contains:
id,first_name,country,day,status
21,Ben,UK,2026-10-27,paid
22,Farhan,India,2026-11-08,paid
23,Asha,India,2026-11-20,pending
24,Dee,Nigeria,2026-11-29,pendingThat opens directly in Excel, Google Sheets or Numbers. For quick exports, psql can also print any query as CSV: psql -d shop --csv -c "SELECT …" > report.csv.
Backing up a whole database
COPY moves one table or query at a time. To back up — or copy — an entire database, structure and data together, use the command-line tools that ship with PostgreSQL:
# back up the shop database to a single compressed file
pg_dump -d shop -Fc -f shop.dump
# restore it into a new, empty database
createdb shop_copy
pg_restore -d shop_copy shop.dump
# or produce a plain .sql script, like the shop.sql you downloaded
pg_dump -d shop -f shop_backup.sqlpg_dump takes a consistent snapshot even while the database is in use. Managed cloud databases also take automatic backups, but a pg_dump before a risky change is a good habit.
A loading checklist
- Look at the file first: header row? delimiter? encoding? date format?
- Create a staging table matching the file.
\copyinto staging, and check the row count matches the file’s line count.- Inspect and clean with
SELECTandUPDATEon the staging table. INSERT … SELECTinto the real tables, inside a transaction.- Drop the staging table.
Tip:
COPYis dramatically faster than individualINSERTs — loading a million rows takes seconds instead of minutes — because the data streams in one operation. Applications that bulk-load data use their driver’s COPY support for the same reason.
Clean up a supplier import
A supplier's CSV has already been loaded with \copy into a staging table — the starter creates it and fills it with the same rows, so you can work anywhere. The data is messy: names have stray spaces, categories are given by name, and one row has a negative price. Write one INSERT … SELECT that loads into products only the rows with a price of 0 or more, with trimmed names, the category id looked up from categories by name (case-insensitively, after trimming), and the price and stock. Then check the result with a SELECT of the products with id > 12, ordered by id — you should see Gooseneck Kettle and Moka Pot (category 3) and Sencha (category 2). Add ORDER BY trim(s.name) to the SELECT so the new ids are given out alphabetically.
-- What \copy produced from the supplier's file:
CREATE TABLE supplier_import (name text, category text, price numeric(10,2), stock integer);
INSERT INTO supplier_import VALUES
(' Sencha ', 'tea', 11.00, 40),
('Moka Pot', ' Equipment', 42.00, 12),
('Broken Kettle', 'Equipment', -1.00, 1),
('Gooseneck Kettle','EQUIPMENT', 64.50, 5);
-- Load the valid rows into products-- What \copy produced from the supplier's file:
CREATE TABLE supplier_import (name text, category text, price numeric(10,2), stock integer);
INSERT INTO supplier_import VALUES
(' Sencha ', 'tea', 11.00, 40),
('Moka Pot', ' Equipment', 42.00, 12),
('Broken Kettle', 'Equipment', -1.00, 1),
('Gooseneck Kettle','EQUIPMENT', 64.50, 5);
-- Load the valid rows into products
INSERT INTO products (name, category_id, price, stock)
SELECT trim(s.name), c.id, s.price, s.stock
FROM supplier_import AS s
LEFT JOIN categories AS c ON lower(c.name) = lower(trim(s.category))
WHERE s.price >= 0
ORDER BY trim(s.name);
SELECT id, name, category_id, price, stock
FROM products
WHERE id > 12
ORDER BY id;Summary
- COPY moves data between a table and a file in bulk, far faster than individual INSERTs; FORMAT csv, HEADER handles typical spreadsheet exports.
- COPY runs on the database server and uses server file paths; psql's \copy reads and writes files on your own computer with the same options.
- Load messy files into a staging table first, then clean, look up keys and validate with INSERT … SELECT.
- Every row is checked against types and constraints; by default one bad row stops the whole load.
- \copy (query) TO 'file.csv' exports any query result; pg_dump backs up a whole database.