Sub topic 1
What COPY Does and Why It Beats Row-by-Row INSERTs
Prerequisites
You should know basic SQL (CREATE TABLE, INSERT, SELECT), be comfortable running psql, understand what a CSV file is, and know basic PostgreSQL data types. The examples use this table:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);What COPY does
COPY moves many rows between a table and a file in one statement. PostgreSQL reads or writes the whole file in a single pass. A loop of INSERT statements sends, parses, and plans each row separately, so COPY is usually much faster for large loads.
Use COPY for data dumps, bulk loads, and report exports. Use INSERT for small, application-driven writes.
A COPY runs as one transaction. If one row fails, the whole load rolls back, so you never end up with a half-loaded table.
Describing your file: the CSV format options
Set these options in WITH (...) so PostgreSQL reads the file correctly:
FORMAT csv: uses CSV quoting rules.HEADER true: skips the first line on import and writes a header line on export.DELIMITER ';': sets the field separator. The CSV default is a comma.QUOTE '"': sets the character that wraps fields. Double quote is the default.NULL 'NULL': sets the text that stands for SQL NULL. The default is an empty unquoted field.ENCODING 'UTF8': sets the file's character encoding.
Importing a CSV file with COPY FROM
Server-side COPY reads a file from the database server's filesystem:
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);The server process needs read access to the file, and your role needs superuser rights or membership in pg_read_server_files. The path refers to the server, not your laptop.
Exercise
What happens if you load a file that has a header row without HEADER true?
Show answer
PostgreSQL reads the header line as a data row. It tries to convert the text "id" to integer, the load fails, and no rows are kept.