Sub topic 12
Speeding Up Large Loads
Assume you know basic SQL, PostgreSQL data types, CSV files, and the psql client. This chapter focuses on performance after you already know how COPY imports and exports data.
Why `COPY` is the starting point
COPY sends many rows through PostgreSQL's bulk-loading path. It avoids the network round trip, parsing, and transaction overhead that occur when an application sends one INSERT statement at a time.
For a large load, use one COPY operation inside one transaction rather than thousands of individual transactions.
psql "$DATABASE_URL" <<'SQL'
BEGIN;
SET LOCAL synchronous_commit = off;
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)
COMMIT;
SQLSET LOCAL synchronous_commit = off allows PostgreSQL to report the commit before the WAL record is safely flushed to disk. This can reduce waiting, but a server crash at that moment can lose the committed transaction. Use it only when the source file can be loaded again and that risk is acceptable.
The setting affects only this transaction because it uses SET LOCAL.
Reduce work during the load
Every index, trigger, and constraint can add work for each imported row. The best approach depends on whether the table is empty or already contains production data.
| Situation | Usual approach |
|---|---|
| New or disposable table | Load first, then create indexes |
| Existing table with required indexes | Keep indexes and load in batches if needed |
| Temporary staging data | Consider an `UNLOGGED` staging table |
| Append-only load | Load, then run `ANALYZE` |
For a new table, create the table without secondary indexes, run COPY, and create the indexes afterward. Building an index once is usually faster than maintaining it during every row insert.
CREATE TABLE products_load (
id integer PRIMARY KEY,
name text NOT NULL,
price numeric(10,2),
released date,
notes text
);
-- Run COPY here, then build additional indexes.
CREATE INDEX products_load_price_idx ON products_load (price);
ANALYZE products_load;Do not remove indexes or disable triggers on a live table without checking their purpose. They may enforce uniqueness, maintain audit records, or protect other tables. Removing them can create invalid data or a long period without required protections.
ANALYZE updates the table's statistics. The query planner uses those statistics to choose efficient plans after the load.
Use staging for disposable or transformable data
An UNLOGGED table does not write its table data to WAL, so loading it can use less I/O. It is not crash-safe, is emptied after an unclean server shutdown, and is not replicated to standby servers. It is suitable only when the data can be recreated.
CREATE UNLOGGED TABLE products_stage (
id integer,
name text,
price numeric(10,2),
released date,
notes text
);
-- Load products_stage with COPY, validate it, then insert into products.
SELECT count(*) FROM products_stage;You can validate and clean the staging rows before inserting into the logged table. This also separates a fast file load from the constraints and indexes on the final table.
Manage WAL, memory, and parallelism
A logged load generates WAL so PostgreSQL can recover the data and replicate it. Large imports therefore need enough disk space for both the table and the WAL stream. If checkpoints occur too often, the load can slow down. A database administrator may tune checkpoint and WAL settings, such as max_wal_size, for a planned bulk load.
Creating indexes after the load uses sort memory. The maintenance_work_mem setting can make that operation faster, but increasing it too far can exhaust server memory when several maintenance jobs run at once.
A single COPY command uses one backend process. Splitting a file into several files and running several COPY commands can improve throughput on a suitable system, but it also increases disk, WAL, index, and lock contention. Test this approach with representative data instead of assuming that more sessions are faster.
flowchart TD
A[Prepare table and file] --> B{Can data be recreated?}
B -->|Yes| C[Use disposable staging table]
B -->|No| D[Use logged table]
C --> E[Load with COPY]
D --> E
E --> F[Create or maintain indexes]
F --> G[ANALYZE]
G --> H[Verify row counts and sample data]Measure before changing settings
Compare the elapsed time, CPU use, disk throughput, WAL volume, and final query performance. A change that shortens the import can still be harmful if it causes replication lag, fills the disk, or leaves the planner with stale statistics.
Avoid treating COPY FREEZE as a general performance switch. It has specific table and transaction conditions and is useful only in narrow loading workflows.
Exercise
A 50-million-row file will be loaded into a new table. Which sequence is usually faster: create all secondary indexes first and then run COPY, or run COPY first and create the indexes afterward?
Show answer
Run COPY first and create the secondary indexes afterward. PostgreSQL can build each index once instead of updating it for every imported row. Run ANALYZE after the load.