Sub topic 12
Speeding up large loads
COPY is already much faster than row-by-row INSERTs. For files with millions of rows, most of the remaining time goes to work around the load: index maintenance, constraint checks, write-ahead logging (WAL), and a single process doing everything. This chapter shows where that time goes and which settings change it.
This chapter assumes you can run COPY and \copy, know the CSV options from earlier chapters, and understand transactions. Examples use the products table from the start of the tutorial.
Measure before you tune
Tuning without a baseline is guesswork. In psql, turn on timing and run the plain load first.
\timing on
TRUNCATE products;
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)Record the time and the row count. Every change below should be compared against this number. On a small file, none of these techniques matter, and the added complexity is not worth it. They start paying off when a load takes minutes.
Where the time goes
COPY parses each line, converts the fields to column types, and writes each row into the table. For every row it also does these things:
- It updates every index on the table.
- It checks constraints and fires any row-level triggers.
- It writes the new row to the WAL, so the change survives a crash and can be replicated.
The parsing cost is fixed. The other three are the levers you can pull.
Load in one transaction
A single COPY statement is already one transaction. If you split a load across many COPY statements, wrap them in one BEGIN ... COMMIT. That commits once, and it also means a failure leaves the table unchanged. Autocommit mode pays a WAL flush for every statement.
Do not make the transaction larger than it needs to be. A very long transaction holds back cleanup of dead rows and keeps locks for its whole duration.
Build indexes after the load
Inserting a million rows into a table with five indexes means five index updates per row, each landing in a different place in the index. Building an index once over finished data is a sort-based bulk operation and is usually much faster.
For a one-off bulk load into a table that nobody else is using, the pattern is:
- Drop the secondary indexes.
- Run COPY.
- Recreate the indexes.
You can raise maintenance_work_mem for the index builds, so they sort in memory instead of spilling to disk. SET LOCAL limits the change to the current transaction.
CREATE INDEX products_released_idx ON products (released);
BEGIN;
SET LOCAL maintenance_work_mem = '1GB';
TRUNCATE products;
DROP INDEX products_released_idx;
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true);
CREATE INDEX products_released_idx ON products (released);
COMMIT;
ANALYZE products;The first CREATE INDEX is only there to make the example runnable from a fresh products table. The DROP INDEX and CREATE INDEX inside the transaction are the actual technique.
Keep the primary key in place unless you have a reason to remove it. Dropping it removes the uniqueness check, so duplicates in the file are no longer caught during the load. Recreating it afterwards fails if duplicates exist, and you would then be debugging a failed index build on a full table.
Dropping indexes has a cost. While the transaction is open, TRUNCATE holds an ACCESS EXCLUSIVE lock, so other sessions cannot read the table. On a live table, this approach is only acceptable in a maintenance window. Otherwise, load into a separate table and swap it in, or keep the indexes and accept the slower load.
Handle constraints and triggers deliberately
Check constraints and NOT NULL are cheap. Foreign keys and triggers are not, because they run work for every row.
- Foreign keys. Each loaded row triggers a lookup in the referenced table. Dropping the constraint before the load and re-adding it with
ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEYafterwards validates everything in one pass, which is usually faster. - User triggers.
ALTER TABLE products DISABLE TRIGGER USERturns off triggers you defined, andENABLE TRIGGER USERturns them back on. Only do this if the trigger logic is not needed for these rows, for example an audit trigger on a bulk migration you will audit another way. - System triggers. Foreign keys are implemented as system triggers.
DISABLE TRIGGER ALLalso disables those and requires superuser. Skipping foreign key checks that way risks loading rows that violate the constraint, and you would not find out.
The safe default is to leave constraints alone and accept the cost. Remove them only when you have measured that they dominate the load time.
Reduce WAL work
Every row COPY writes normally also goes to the WAL. There are two ways to avoid some of that cost, and both have trade-offs.
Same-transaction creation or truncation
If the table is created or truncated in the same transaction as the COPY, and the server runs with wal_level = minimal, PostgreSQL can skip WAL for the loaded data. It makes sure the data is flushed to disk at commit instead. The default wal_level is replica, so this does not apply unless your administrator has set minimal. That setting is incompatible with replication and with WAL-based archiving, so you cannot change it casually.
COPY FREEZE
FREEZE loads rows already marked as frozen. That saves a later vacuum from having to rewrite those pages, which matters after a big load into a large table. It has the same precondition as above: the table must be created or truncated in the same transaction.
BEGIN;
TRUNCATE products;
COPY products FROM '/var/lib/postgresql/import/products.csv'
WITH (FORMAT csv, HEADER true, FREEZE true);
COMMIT;Known restrictions:
- It does not work on partitioned tables or foreign tables.
- It raises an error if the table was not created or truncated in the current transaction.
- Rows are visible to other sessions' existing snapshots immediately after commit. A long-running repeatable-read transaction that started before your load may therefore see the new rows, which breaks normal snapshot isolation. This is acceptable for a controlled reload and a poor choice on a busy shared table.
Unlogged staging tables
An unlogged table skips WAL entirely. Data in it is lost after a crash and is not replicated. That is a good fit for a staging table whose contents you can reload from the file.
CREATE UNLOGGED TABLE products_stage (LIKE products);
\copy products_stage FROM 'products.csv' WITH (FORMAT csv, HEADER true)
INSERT INTO products
SELECT * FROM products_stage
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price,
released = EXCLUDED.released,
notes = EXCLUDED.notes;
DROP TABLE products_stage;The final INSERT into products is still logged. The gain is limited to the first step. Use this when staging, cleanup, or validation takes a large share of the time. For a direct load into the final table, it does not help.
Do not make the real target table unlogged unless losing it in a crash is acceptable. A crash empties an unlogged table.
Run several COPY commands in parallel
A single COPY statement uses one server process. Splitting the input and loading the pieces over separate connections uses more CPU cores and more disk bandwidth. Rows are inserted independently, so the load order does not matter for a heap table.
tail -n +2 products.csv | split -l 500000 - chunk_
ls chunk_* | xargs -P 4 -I{} \
psql "$DATABASE_URL" -c "\copy products FROM '{}' WITH (FORMAT csv)"The tail -n +2 removes the header line, so the chunks are loaded without HEADER. -P 4 runs four psql processes at a time.
This approach has real limits:
split -lcuts by line. A quoted field that contains a newline can be cut in half and the chunks become invalid CSV. Only split files you know have no embedded newlines, or use a CSV-aware splitter.- The parallel loads are separate transactions, so the load is no longer all-or-nothing. If one chunk fails, the others may already be committed. Keep a record of which chunks finished.
FREEZEcannot be used, because the table cannot be truncated in the same transaction as each separate load.- Parallel inserts into one table with indexes contend on those indexes. Parallelism helps most when the indexes are dropped first. Past a few connections you will see diminishing returns, so measure with 2, 4, and 8.
Other settings worth knowing
| Setting or choice | Effect | Caveat |
|---|---|---|
| Larger `max_wal_size` | Fewer forced checkpoints during a heavy load | Needs more disk for WAL and lengthens crash recovery |
| Larger `maintenance_work_mem` | Faster `CREATE INDEX` and `ADD FOREIGN KEY` afterwards | Memory is allocated per operation |
| Matching file and database encoding | Avoids per-field conversion | Re-encoding the file with `iconv` beforehand costs time too |
| `FORMAT binary` | Skips text parsing | Not CSV, tied to PostgreSQL's internal formats, and mostly useful for moving data between PostgreSQL databases |
| `ANALYZE` after the load | Gives the planner correct statistics | Autovacuum may do this eventually, but not before your first queries |
Run ANALYZE on the table after any large load. Without it, the planner may use outdated row counts and choose poor plans for the queries that follow.
A load checklist
Apply these in order and stop as soon as the load is fast enough:
- Load with a plain COPY in one transaction and record the time.
- If the table has several indexes, drop them and rebuild after the load.
- If you reload the whole table, add
TRUNCATEandFREEZEin the same transaction. - If foreign keys or triggers dominate, drop and re-add the constraint, or disable user triggers.
- If the file is large and splittable, load chunks in parallel.
- Run
ANALYZE, then verify the row count against the source.
Verification matters more after tuning, because several of these techniques loosen safety checks. Compare the loaded count with the file's line count, minus the header.
Exercise
You must reload all 20 million rows of a products table every night. The table has a primary key and three secondary indexes. Nobody queries it during the 02:00 maintenance window. Describe a load plan in a single transaction, and name one reason COPY ... FREEZE could be a poor choice for a different table.
Show answer
Begin a transaction, set maintenance_work_mem with SET LOCAL, TRUNCATE products, drop the three secondary indexes, run COPY ... WITH (FORMAT csv, HEADER true, FREEZE true), recreate the three indexes, and commit. Keep the primary key so duplicates in the file are still rejected. Run ANALYZE products afterwards. FREEZE would be a poor choice on a busy shared table that cannot be truncated, because it requires the table to be created or truncated in the same transaction. It also does not work on partitioned tables, and sessions with older snapshots may see the new rows.
Exercise
A colleague splits a CSV file with split -l 500000 and loads the chunks in parallel with four \copy commands. One chunk fails midway through. What is the state of the table, and what is one reason a chunk might fail even if the original file was valid?
Show answer
Each chunk is its own transaction, so chunks that finished are committed and the failed chunk added nothing. The table is partly loaded. You must track which chunks succeeded and reload only the failed one. A chunk can fail even if the original file was valid when split cuts through a quoted field that contains a newline, which leaves an unterminated quote in one chunk and a stray fragment in the next.