Nov 23, 20266 min read

Bulk Insert into Postgres: Multi-Row INSERT, UNNEST and COPY

Why inserting rows one at a time is slow, how multi-row VALUES, UNNEST arrays and COPY compare on 100,000 rows, how to upsert in bulk, and a Go example on Encore.

Illustration for Bulk Insert into Postgres: Multi-Row INSERT, UNNEST and COPY

Inserting rows one at a time works until an import or a backfill hands your API 50,000 of them. Each INSERT is a round trip and often its own commit, and a job that took a second in development takes minutes against a remote database.

This guide compares the three faster options with real timings and shows the Go code for each.

Why are row-by-row inserts slow?

Every statement pays for a round trip to the server, parsing and planning, and a WAL flush if it commits on its own. On a local database over a Unix socket that is around 50 microseconds per row. Over a real network with a millisecond of latency it becomes a millisecond or more per row, which is why 100,000 single-row inserts can run for minutes. The Postgres guide to populating a database lists the standard fixes: batch rows into fewer statements, wrap them in one transaction and use COPY where you can.

How do the bulk insert methods compare?

We loaded 100,000 rows of (sku text primary key, qty int) into Postgres 17 on the same machine, over a Unix socket, using Go and pgx. Network latency would make the row-by-row number much worse and barely change the others.

MethodTime for 100,000 rowsUpsert supportStatement size
Row by rowAbout 5 s (0.50 s per 10,000)YesOne per row
Multi-row VALUES, 1,000 rows each0.64 sYesGrows with rows
INSERT ... SELECT FROM unnest(...)0.23 sYesFixed
COPY (pgx CopyFrom)0.17 sNoStreamed

Upserting the same 100,000 rows again with unnest and ON CONFLICT DO UPDATE took 0.70 s, since every row became an update.

When should you use multi-row VALUES?

When an ORM or query builder generates it for you and batches stay small. The statement text grows with every row, and the Postgres wire protocol caps a statement at 65,535 bind parameters, so a 10-column table can insert at most 6,553 rows per statement and a hand-built query has to chunk the input.

Why is UNNEST the best default for APIs in our local Postgres 17 benchmark?

unnest turns one array parameter per column into rows inside the database, so the statement text never changes, the parameter limit does not apply and the planner can cache it. It works with ON CONFLICT, RETURNING and joins, which covers the "insert or update this batch" case most APIs have:

INSERT INTO stock_levels (sku, quantity, updated_at) SELECT sku, qty, now() FROM unnest($1::text[], $2::int[]) AS t(sku, qty) ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity, updated_at = now();

The one rule to remember is that a batch must not contain the same key twice, or Postgres stops with "ON CONFLICT DO UPDATE command cannot affect row a second time". Deduplicate in application code before the call.

When is COPY worth it?

For append-only data where you load very large batches, such as event history, imports into a fresh table or backfills. COPY streams rows in the binary protocol without per-row statements, and it is the fastest option in our local Postgres 17 benchmark, but it cannot upsert and a single bad row aborts the whole load. For upserts with COPY speed, copy into a temporary table first and then run one INSERT ... SELECT ... ON CONFLICT from it.

Bulk inserts with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the database these batches go into is declared in the Go service itself. The Postgres database gets its tables from migration files, db.Exec runs the unnest upsert with Go slices as array parameters, and sqldb.Driver hands you the underlying pgx pool when you want CopyFrom. When deployed, the same database runs on RDS or Cloud SQL in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- inventory/migrations/1_create_inventory.up.sql CREATE TABLE stock_levels ( sku TEXT PRIMARY KEY, quantity INT NOT NULL, updated_at TIMESTAMPTZ NOT NULL ); CREATE TABLE stock_movements ( sku TEXT NOT NULL, delta INT NOT NULL, occurred_at TIMESTAMPTZ NOT NULL ); CREATE INDEX stock_movements_sku_time ON stock_movements (sku, occurred_at);
// inventory/bulk.go package inventory import ( "context" "time" "encore.dev/storage/sqldb" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) var db = sqldb.NewDatabase("inventory", sqldb.DatabaseConfig{Migrations: "./migrations"}) type StockLevel struct { SKU string Quantity int32 } type UpsertLevelsParams struct { Levels []StockLevel } type Result struct { Rows int64 } // UpsertLevels writes a batch of stock levels in one statement. // //encore:api private method=POST path=/inventory/levels func UpsertLevels(ctx context.Context, p *UpsertLevelsParams) (*Result, error) { // The last value for a SKU wins; duplicates in one batch would make ON CONFLICT fail. latest := make(map[string]int32, len(p.Levels)) for _, l := range p.Levels { latest[l.SKU] = l.Quantity } skus := make([]string, 0, len(latest)) qtys := make([]int32, 0, len(latest)) for sku, q := range latest { skus = append(skus, sku) qtys = append(qtys, q) } res, err := db.Exec(ctx, ` INSERT INTO stock_levels (sku, quantity, updated_at) SELECT sku, qty, now() FROM unnest($1::text[], $2::int[]) AS t(sku, qty) ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity, updated_at = now()`, skus, qtys) if err != nil { return nil, err } return &Result{Rows: res.RowsAffected()}, nil } type Movement struct { SKU string Delta int32 OccurredAt time.Time } type RecordMovementsParams struct { Movements []Movement } // RecordMovements appends history rows with COPY, the fastest path for insert-only data in our local Postgres 17 benchmark. // //encore:api private method=POST path=/inventory/movements func RecordMovements(ctx context.Context, p *RecordMovementsParams) (*Result, error) { pool := sqldb.Driver[*pgxpool.Pool](db) n, err := pool.CopyFrom(ctx, pgx.Identifier{"stock_movements"}, []string{"sku", "delta", "occurred_at"}, pgx.CopyFromSlice(len(p.Movements), func(i int) ([]any, error) { m := p.Movements[i] return []any{m.SKU, m.Delta, m.OccurredAt}, nil }), ) if err != nil { return nil, err } return &Result{Rows: n}, nil }

encore run starts Postgres locally and applies the migration, so you can post a 50,000-row batch to /inventory/levels and see the single statement and its duration in the local trace. For imports larger than one request body, put the file in an object storage bucket and have a Pub/Sub subscriber read it in chunks of 10,000 rows, calling the same upsert per chunk.

An agent asked to "make the import faster" can switch a loop of single inserts to the unnest form, run the existing import test against the local database and compare the timings in the traces before and after.

Best fit: Services that ingest batches from imports, syncs or devices and want them in their own Postgres database with one statement per batch.

Frequently asked questions

What is the fastest way to bulk insert into Postgres in a local benchmark?

In our local Postgres 17 benchmark, COPY is the fastest, followed closely by a single INSERT that reads from UNNEST over arrays. Both send the data in one round trip. Inserting row by row is the slowest by far because every row costs a network round trip and, outside a transaction, a commit.

Can COPY do an upsert in Postgres?

No. COPY only inserts and fails on a unique violation. For bulk upserts, use INSERT ... SELECT FROM unnest(...) ON CONFLICT DO UPDATE, or COPY into a temporary staging table and then run one INSERT ... SELECT ... ON CONFLICT from it.

How many rows can one multi-row INSERT have?

The limit is on parameters, not rows: the Postgres wire protocol allows at most 65,535 bind parameters per statement, so a table with 10 columns tops out at 6,553 rows per INSERT. UNNEST avoids the limit because each column is a single array parameter.

How do I bulk insert with Encore?

Use db.Exec with an INSERT ... SELECT FROM unnest($1::text[], $2::int[]) statement for inserts and upserts, and call sqldb.Driver to get the pgx pool when you need CopyFrom. Both work against the Postgres database that encore run starts locally.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders