Bulk Data Loading (COPY, CSV Imports & Exports)
Load and export large CSV/TSV datasets efficiently with COPY and client tools.
In plain words
COPY loads a whole file into a table in one go, much faster than inserting rows one by one.
Think of it like…
Moving house with a truck instead of carrying boxes one at a time by hand: the truck (COPY) loads everything in one trip, but you still check the boxes before unpacking them into the right rooms (the staging step).
Where you’ve seen it
A nightly partner file with 5 million rows: \copy staging_orders FROM 'orders_2026-11-20.csv' WITH (FORMAT csv, HEADER) takes under a minute; a validation query finds 42 rows with negative amounts; an upsert moves the clean rows into orders; ANALYZE orders refreshes statistics.
Words you’ll hear
- COPY
- PostgreSQL's bulk import/export command; runs on the database server.
- \copy
- psql's client-side version that reads or writes files on your machine.
- Staging table
- A loose, unindexed table for raw data before validation.
- LOAD DATA INFILE
- MySQL's bulk loader; LOCAL reads from the client.
Visual diagram
Theory & example queries
COPY and its options
COPY staging_orders FROM '/data/orders.csv' WITH (FORMAT csv, HEADER, DELIMITER ',', NULL '') reads a file that must exist on the database server and needs elevated privileges (superuser or the pg_read_server_files role). From your laptop or an application, use psql's \copy (same options, client-side) or the driver's COPY support (for example copy_expert in psycopg).
Options cover most real-world mess: FORMAT csv handles quoted fields with commas inside; HEADER skips the first line; NULL defines how missing values appear; ENCODING fixes character set mismatches; FORCE_NULL treats empty quoted strings as NULL. COPY is all-or-nothing by default: one malformed row aborts the whole load. PostgreSQL 17 added ON_ERROR ignore to skip bad rows.
\copy (SELECT id, amount, created_at FROM orders WHERE created_at >= '2026-11-01') TO 'november_orders.csv' WITH (FORMAT csv, HEADER)
A robust load process
Load into a staging table whose columns are mostly text, so formatting problems don't abort the load. Then validate with SQL (bad dates, negative amounts, unknown foreign keys), report or quarantine the bad rows, and move clean rows into the real table with INSERT … SELECT or an upsert, casting types along the way.
For very large initial loads, it's faster to create indexes and foreign keys after loading rather than maintaining them row by row, and to load in one transaction. Run ANALYZE on the target afterwards so the planner knows its new size. MySQL's equivalent is LOAD DATA LOCAL INFILE … (with local_infile enabled), and cloud warehouses load from object storage (COPY INTO in Snowflake, bq load in BigQuery).
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
INSERT INTO orders (external_id, amount, created_at)SELECT external_id, amount::numeric, created_at::timestamptzFROM staging_ordersWHERE amount ~ '^[0-9]+(\.[0-9]{1,2})?$'ON CONFLICT (external_id) DO UPDATESET amount = EXCLUDED.amount;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative PostgreSQL status for 240 valid staging rows; it counts inserts and updates together.
Key takeaway: Stage, validate, upsert, ANALYZE.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Create a staging table
Create an unindexed table matching the file's columns, mostly as text, so every row loads.
CREATE UNLOGGED TABLE staging_orders ( external_id text, amount text, created_at text)When to use it & trade-offs
What it is
Bulk loading moves large files into tables far faster than INSERT statements. PostgreSQL's COPY table FROM 'file' WITH (FORMAT csv, HEADER) reads a file on the database server; psql's \copy reads a file on your own machine. COPY … TO exports. MySQL uses LOAD DATA [LOCAL] INFILE. The usual pattern is to load raw data into a staging table, validate it, then transform it into the real tables.
Why it matters: Importing CSVs from partners, migrating data and loading warehouse tables all involve millions of rows. Done row by row, an import takes hours; with COPY it takes seconds or minutes. Getting delimiters, NULLs, encodings and bad rows right is where the real work is.
When to reach for it
- Importing partner or vendor CSV files
- Initial data migrations
- Exporting query results to CSV
When to avoid or be careful
- Loading straight into the final table with strict types and constraints
- Looping single-row inserts for big files
- Forgetting ANALYZE after a large load
COPY vs batched INSERT vs single-row INSERT
Strengths: By far the fastest; streams data efficiently.
Watch out: Stops on the first bad row (unless configured); needs file access or a client wrapper.
Strengths: Works through any driver; per-batch error handling.
Watch out: Slower than COPY for very large loads.
Strengths: Simple.
Watch out: Hours for millions of rows.
Interview signals & numbers to know
When this topic comes up
- “Import this 2 GB CSV”
- “The import takes hours”
- “must be superuser to COPY from a file”
- Data migration
- ETL / ELT
Benchmarks & rules of thumb
- \copy
- client-side COPY in psql
- PostgreSQL 17
- COPY ON_ERROR ignore
- 1
- bad row stops a default COPY
Common mistakes & follow-ups
Common interview mistakes
- Running COPY FROM with a path on your laptop and getting "could not open file" because COPY reads from the server.
- Loading into typed columns and having the whole import fail on one malformed date.
- Not specifying FORMAT csv, so quoted fields with commas split into the wrong columns.
Likely interviewer follow-ups
- How would you load a 5-million-row CSV into PostgreSQL quickly and safely?
- What's the difference between COPY and \copy?
- How do you handle bad rows during a bulk load?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Bulk Data Loading (COPY, CSV Imports & Exports) with hands-on SQL practice and interview Q&A.