Part 11 / Topic 7 of 7
Bulk loading: COPY and \copy
Row-by-row INSERTs are fine for rows; for files there is COPY — the bulk pipe, an order of magnitude faster than looped inserts. Loading inline (stdin) works anywhere psql does:
CREATE TABLE price_import (sku text, price numeric(10,2));
COPY price_import FROM stdin WITH (FORMAT csv);
chai-250,120.00
coffee-500,340.00
filter-papers,95.00
\.
SELECT * FROM price_import ORDER BY sku;
CREATE TABLE
COPY 3
sku | price
---------------+--------
chai-250 | 120.00
coffee-500 | 340.00
filter-papers | 95.00
(3 rows)
For files, the names matter:
COPY table FROM '/path/file.csv'runs on the server — the file must sit on the database machine, and reading it needs superuser or thepg_read_server_filesrole.\copy table FROM 'file.csv'is psql's client-side twin — your machine's file, streamed over the connection, ordinary privileges. This is the one you'll actually use.
The professional load pattern stitches this part together: \copy into a staging table, validate/clean with SQL, then INSERT ... SELECT or MERGE into the real table — bulk speed, with constraints and dedup logic applied deliberately in between.
🧪 Quick quiz — answer from memory, then check.
- COPY vs \copy — whose filesystem?
- Why stage bulk loads instead of COPYing straight into the real table?
Show the answers
- COPY reads the server's disk (privileged); \copy streams the client's file through psql.
- Validate, dedupe and transform with SQL between the raw file and the constrained table — bad rows get handled, not half-loaded.
Exercise 7: Stage, then merge
What to do: The professional load: COPY a three-line supplier CSV (TechSource/India, Nordic Parts/Sweden, PageTurners/UK) into a staging table, then insert into suppliers only the genuinely new one, returning it.
Sample output:
supplier_id | name | country
-------------+--------------+---------
4 | Nordic Parts | Sweden
(1 row)
💡 Hint: COPY ... FROM stdin WITH (FORMAT csv) (or \copy from a real file), then INSERT ... SELECT ... WHERE NOT EXISTS.
Show the solution to Exercise 7
-- Exercise 7: Stage, then merge (the professional load)
DROP TABLE IF EXISTS supplier_import;
CREATE TABLE supplier_import (name text, country text);
COPY supplier_import FROM stdin WITH (FORMAT csv);
TechSource,India
Nordic Parts,Sweden
PageTurners,UK
\.
-- Only genuinely new suppliers cross over (dedup by name in staging SQL):
INSERT INTO suppliers (name, country)
SELECT i.name, i.country
FROM supplier_import AS i
WHERE NOT EXISTS (SELECT 1 FROM suppliers s WHERE s.name = i.name)
RETURNING supplier_id, name, country;