SQL · Module 3 · Lesson 51 min read

Importing & Exporting CSV (COPY)

COPY – the fastest way to load and export data

Import (CSV → table)

SQL
COPY expenses (user_id, title, amount, spent_on)
FROM '/path/expenses.csv'
WITH (FORMAT csv, HEADER true);

Export (table/query → CSV)

SQL
COPY (SELECT * FROM expenses WHERE amount > 1000)
TO '/path/big.csv'
WITH (FORMAT csv, HEADER true);

COPY vs \copy ⚠️

  • COPY … FROM '/file' reads the file on the database server (needs special permissions)
  • \copy (a psql command) reads the file on your computer and streams it ✅ usually what you want \copy expenses (title, amount) FROM 'data.csv' WITH (FORMAT csv, HEADER)
  • COPY … FROM STDIN / TO STDOUT – stream data through your client or app

Useful options

  • HEADER true – the first line has column names
  • DELIMITER ';' – for semicolon-separated files
  • NULL '' – which text means NULL
  • QUOTE '"', ENCODING 'UTF8'
  • FORCE_NULL (col), FORCE_QUOTE *

Import tips

  1. Load into a staging table first (all columns as TEXT), then clean and convert with INSERT … SELECT
  2. Check for bad rows: wrong dates, "1,200" with commas, extra spaces, blank lines
  3. Use ON CONFLICT DO NOTHING when re-importing
  4. Big loads: drop indexes first and recreate after, or load in batches

Other ways

  • Supabase: Table Editor → "Import data from CSV"
  • pgAdmin / DBeaver: right-click a table → Import/Export
  • Spreadsheet → Save As CSV (UTF-8) first
  • Export JSON: SELECT json_agg(e) FROM expenses e;

Example

SQL
-- 1. Export a report to CSV (shown on screen via STDOUT; use a file path or \copy for files)
COPY (
  SELECT u.name, e.title, e.amount, e.spent_on
  FROM expenses e JOIN users u ON u.id = e.user_id
  WHERE e.amount >= 5000
  ORDER BY e.amount DESC
) TO STDOUT WITH (FORMAT csv, HEADER true);
-- name,title,amount,spent_on
-- Ravi Thapa,Paragliding,8500.00,2026-11-02
-- ...

-- In psql, save to a file on YOUR computer:
-- \copy (SELECT * FROM expenses) TO 'expenses.csv' WITH (FORMAT csv, HEADER)

-- 2. Import safely through a staging table
CREATE TEMP TABLE staging_expenses (
  email TEXT, title TEXT, amount TEXT, spent_on TEXT
);

-- \copy staging_expenses FROM 'bank_export.csv' WITH (FORMAT csv, HEADER)
-- (simulating the file contents here:)
INSERT INTO staging_expenses VALUES
  ('asha@example.com', ' Pharmacy ', '1,250.00', '2026-11-14'),
  ('ravi@example.com', 'Gym',        '2000',     '2026-11-15'),
  ('nobody@example.com', 'Ghost',    '100',      '2026-11-15');   -- unknown user

-- 3. Clean, convert and insert only valid rows
INSERT INTO expenses (user_id, title, amount, spent_on)
SELECT u.id,
       trim(s.title),
       replace(s.amount, ',', '')::numeric,
       s.spent_on::date
FROM staging_expenses s
JOIN users u ON u.email = s.email            -- skips unknown users
RETURNING user_id, title, amount;            -- 2 rows

-- 4. Export as JSON
SELECT json_agg(b) FROM bills b WHERE NOT paid;