Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 35/ 160
02. Aggregations, Functions & Data Manipulation

Bulk Data Loading (COPY, CSV Imports & Exports)

Load and export large CSV/TSV datasets efficiently with COPY and client tools.

IntermediateCOPY · CSV Import3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Export a report to CSV

\copy (SELECT id, amount, created_at FROM orders WHERE created_at >= '2026-11-01') TO 'november_orders.csv' WITH (FORMAT csv, HEADER)

Key takeaway: COPY for server files, \copy for client files; options handle CSV quirks.

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).

Staging to target with validationQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1INSERT INTO2  orders (external_id, amount, created_at)3SELECT4  external_id,5  amount::numeric,6  created_at::timestamptz7FROM8  staging_orders9WHERE10  amount ~ '^[0-9]+(\.[0-9]{1,2})?$'11ON CONFLICT (external_id) DO UPDATE12SET13  amount = EXCLUDED.amount;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
INSERT 0 240

Note: Representative PostgreSQL status for 240 valid staging rows; it counts inserts and updates together.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Stage, validate, upsert, ANALYZE.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Schema

Create a staging table

Create an unindexed table matching the file's columns, mostly as text, so every row loads.

SQL at this step
1CREATE UNLOGGED TABLE staging_orders (2  external_id text,3  amount text,4  created_at text5)
What to watch at this step
UNLOGGED
faster, not crash-safe
Tip: use ← → to move between steps

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

COPY / LOAD DATA
Best for: Files with thousands to billions of rows

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.

Batched multi-row INSERT
Best for: Application-generated data in moderate volumes

Strengths: Works through any driver; per-batch error handling.

Watch out: Slower than COPY for very large loads.

Single-row INSERT
Best for: Individual user actions

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?
Interview tip: Describe the stage → validate → upsert → ANALYZE process. It shows you think about data quality, not just speed.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Upserts (INSERT ... ON CONFLICT DO UPDATE / DO NOTHING, MERGE)
Next topic
Generating Series & Synthetic Data (GENERATE_SERIES)