# The fastest way to bulk insert into Postgres: 7 methods measured at 0.1, 2 and 8 ms of latency

Row-by-row INSERT, one big transaction, executemany with pipeline mode, multi-row VALUES, unnest arrays and COPY, timed on PostgreSQL 17.11 with 10,000 rows and three network round-trip times. Why COPY is ~100× faster on localhost and over 1,000× faster over a network, and what changes behind a transaction pooler.

**"How do I insert a lot of rows into Postgres quickly?" has a textbook answer: use `COPY`. What the textbook doesn't tell you is how much the answer depends on the network. We loaded the same 10,000 rows into PostgreSQL 17.11, the major version Relyt One runs, seven different ways, with the client next to the server and then with 2 ms and 8 ms of round-trip time added. On localhost, `COPY` was about 100 times faster than inserting one row at a time. With 8 ms between client and database, it was over 1,000 times faster, and the row-by-row load took a minute and a half. The one surprise was `executemany()` in psycopg 3: it barely noticed the latency. Every number below was measured, and the code for each method is in the post.**

## The short version

Time to insert 10,000 rows (median of three runs). The round-trip time is what we measured with `SELECT 1` from the client.

| Method (s)                                   | 0.1 ms | 2 ms  | 8 ms  |
| -------------------------------------------- | ------ | ----- | ----- |
| One `INSERT` per row, autocommit             | 1.55   | 32.1  | 88.6  |
| Same, with `synchronous_commit = off`        | 0.76   | 31.4  | 88.1  |
| One `INSERT` per row, one transaction        | 0.75   | 28.0  | 84.2  |
| `executemany()` (psycopg pipeline mode)      | 0.090  | 0.097 | 0.111 |
| Multi-row `VALUES`, 1,000 rows per statement | 0.084  | 0.118 | 0.216 |
| `INSERT … SELECT FROM unnest(arrays)`        | 0.059  | 0.078 | 0.136 |
| `COPY … FROM STDIN`                          | 0.016  | 0.030 | 0.078 |

![Time to insert 10,000 rows, log scale: row-by-row methods take about a second locally and over 80 seconds at 8 ms; batched methods stay under a quarter of a second](/blog/assets/26244645c3a31630.svg)

- **Round trips decide everything once there's a network.** The three row-by-row methods wait for the server after every row, so at 8 ms each row costs about 8.8 ms, no matter how you commit.
- **Committing once matters most on localhost.** There, about half the cost of autocommit is waiting for the WAL flush of 10,000 commits. Over a network it still saved about 4 s, but that's 5–13% of the total; the wait for each row dominates.
- **Everything batched stays under a quarter of a second**, even at 8 ms. `COPY` is fastest everywhere; `executemany()` in pipeline mode is the easiest to adopt if your code already inserts one row at a time.

## How we tested

Everything ran in throwaway Docker containers on an Apple M1 Pro laptop (5 CPUs and 12 GB of memory given to Docker): `postgres:17.11-alpine` with default settings (`shared_buffers` 128 MB, `synchronous_commit` on), and a client container with Python 3.12 and psycopg 3.2.3. To add latency we gave the client container the `NET_ADMIN` capability and ran `tc qdisc add dev eth0 root netem delay 1ms` (or `5ms`). That delays every packet the client sends. We measured the resulting round trip with 20 `SELECT 1` queries: 0.10 ms without delay, 2.09 ms with `1ms` and 7.84 ms with `5ms`. We report the measured values, not the `netem` settings.

The table is the kind of thing you'd bulk-load in real life, an events table with an identity primary key:

```sql
CREATE TABLE events (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id    int         NOT NULL,
  kind       text        NOT NULL,
  note       text        NOT NULL,
  created_at timestamptz NOT NULL
);
```

Each method ran three times on a fresh connection after a `TRUNCATE`, and the script checks that exactly 10,000 rows arrived. We also ran the localhost case with 100,000 rows: rows per second came out within 13% of the 10,000-row numbers for every method, so the smaller load isn't hiding much of a startup cost. Absolute times depend on the laptop; the ratios between methods are the part to take away. The code for each method is in its section below.

## Result 1: row by row, the round trip is the bill

The naive loop sends one `INSERT`, waits for the answer, then sends the next:

```python
for row in rows:
    cur.execute(
        "INSERT INTO events (user_id, kind, note, created_at) VALUES (%s, %s, %s, %s)",
        row)
```

On localhost that's 1.55 s for 10,000 rows, about 0.16 ms a row. The [PostgreSQL docs on populating a database](https://www.postgresql.org/docs/17/populate.html) tell you to turn off autocommit and commit once at the end, because "if you allow each insertion to be committed separately, PostgreSQL is doing a lot of work for each row that is added." That work is mostly making each commit durable. Our numbers agree: one transaction halved the time to 0.75 s, and so did keeping autocommit but setting `synchronous_commit = off` (0.76 s), which stops each commit from waiting for its WAL flush.

Then add a network. At a 2 ms round trip the same loop takes 32 s; at 8 ms, 88.6 s. Committing once saves 4 s out of 88. Each row costs about one measured round trip plus another millisecond: about 3.2 ms at 2 ms and 8.8 ms at 8 ms. No amount of server tuning helps here, because the server is idle most of the time, waiting for the next row.

This matters for hosted Postgres in general, not just for us. A local database has a round trip around 0.1 ms, so a row-by-row import that "works fine in development" can get 20 to 100 times slower the day the database moves a few milliseconds away (21 times at 2 ms and 57 times at 8 ms in our autocommit loop), without a single query plan changing.

## Result 2: `executemany()` in pipeline mode hides the latency

psycopg 3 has a cheap fix for code shaped like the loop above:

```python
with conn.transaction(), conn.cursor() as cur:
    cur.executemany(
        "INSERT INTO events (user_id, kind, note, created_at) VALUES (%s, %s, %s, %s)",
        rows)
```

It's still one `INSERT` per row on the server. The difference is on the wire: [starting from psycopg 3.1](https://www.psycopg.org/psycopg3/docs/advanced/pipeline.html), `executemany()` uses libpq's pipeline mode internally. The client sends the statements without waiting for each result and reads the results as they come back, so the round trip is paid a handful of times instead of 10,000 times. The time went from 0.090 s on localhost to 0.111 s at 8 ms. That's 800 times faster than the plain loop at 8 ms, for a one-line change.

Three caveats. Not every driver does this: check whether yours pipelines or batches its "execute many" call, or just loops. It's still 10,000 statements of work for the server, which is why it's slower than `unnest` and `COPY` on localhost. And it leans on prepared statements: with psycopg's default settings the `INSERT` is prepared after a few executions, and with preparing turned off (see the pooler section below) the same call took 0.199 s locally instead of 0.090 s.

## Result 3: multi-row `VALUES` and `unnest`

The classic batch is one `INSERT` with many rows:

```sql
INSERT INTO events (user_id, kind, note, created_at) VALUES
  (1, 'click', 'first',  '2026-01-01 00:00:00+00'),
  (2, 'view',  'second', '2026-01-01 00:00:01+00'),
  (3, 'buy',   'third',  '2026-01-01 00:00:02+00');
```

With 1,000 rows per statement, 10,000 rows took 0.084 s locally and 0.216 s at 8 ms. It's ten statements, so at least ten waits, and the latency shows more than it does for the pipelined `executemany()`. You can't make the batches as big as you like when you pass the values as parameters: the wire protocol counts parameters in a 16-bit field. With four columns, 16,383 rows (65,532 parameters) went through; 16,384 rows failed in the client with `number of parameters must be between 0 and 65535`. With wider tables the limit arrives sooner.

`unnest` avoids the limit by sending one array per column instead of one parameter per value. The statement has four parameters whatever the row count:

```sql
INSERT INTO events (user_id, kind, note, created_at)
SELECT * FROM unnest(
  $1::int[],         -- every user_id
  $2::text[],        -- every kind
  $3::text[],        -- every note
  $4::timestamptz[]  -- every created_at
);
```

From Python, pass one list per column: `cur.execute(sql_with_%s_placeholders, [list(col) for col in zip(*rows)])`. It was the fastest `INSERT` on localhost and at 2 ms (0.059 s and 0.078 s), and took 0.136 s at 8 ms. Because it's a normal `INSERT … SELECT`, it also works with `ON CONFLICT`, `RETURNING` and joins against other tables, which `COPY` can't do. With 8 ms of latency, the pipelined `executemany()` beat it by a small margin. We didn't trace the packets, but a single statement carrying 10,000 rows of arrays is one big request the server can only start on once it has arrived, while the pipeline lets the server work while the rest is still on its way.

## Result 4: `COPY` is still the fastest

`COPY` is the bulk-loading command; the docs say loading with it "is almost always faster than using `INSERT`, even if `PREPARE` is used and multiple insertions are batched into a single transaction." It doesn't parse and plan one statement per row and the data streams in its own format. In psycopg 3:

```python
with conn.transaction(), conn.cursor() as cur:
    with cur.copy("COPY events (user_id, kind, note, created_at) FROM STDIN") as copy:
        for row in rows:
            copy.write_row(row)
```

10,000 rows took 0.016 s locally, about 640,000 rows a second, and 0.078 s at 8 ms. At 8 ms that's 1,135 times faster than the row-by-row loop with autocommit.

`COPY FROM STDIN` means the data comes from the client over the connection, which is what you want with a hosted database. `COPY … FROM '/path/file.csv'` reads a file on the database server instead, and is limited to superusers and roles with the privileges of `pg_read_server_files`. As an ordinary role, Postgres 17 refuses with `permission denied to COPY from a file` and the hint "Anyone can COPY to stdout or from stdin." From `psql`, `\copy` reads a file on your machine and streams it with `COPY FROM STDIN`:

```sql
\copy events (user_id, kind, note, created_at) FROM 'events.csv' WITH (FORMAT csv, HEADER true)
```

### Two things `COPY` doesn't do, and the workarounds

**No `ON CONFLICT`.** `COPY` only inserts. To upsert a file, copy it into a staging table and upsert from there, which gives you the [usual `ON CONFLICT` choices](/blog/postgres-upsert-on-conflict-vs-merge):

```sql
CREATE TEMP TABLE events_staging (user_id int, kind text, note text, created_at timestamptz);
\copy events_staging FROM 'events.csv' WITH (FORMAT csv, HEADER true)

INSERT INTO events (user_id, kind, note, created_at)
SELECT user_id, kind, note, created_at FROM events_staging
ON CONFLICT (user_id, created_at) DO UPDATE SET note = EXCLUDED.note;
```

(This needs a unique index on `(user_id, created_at)`, which our benchmark table doesn't have. Run it on the direct connection: behind a transaction pooler, each statement can land on a different server connection, and the temp table won't be there.)

**One bad row used to abort the whole load.** Before Postgres 17, a single line that doesn't parse failed the entire `COPY`. Postgres 17 added `ON_ERROR ignore`, which skips rows whose values can't be converted to the column type, and `LOG_VERBOSITY verbose`, which tells you which ones:

```sql
\copy events (user_id, kind, note, created_at) FROM 'bad.csv' WITH (FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose)
```

```
NOTICE:  skipping row due to data type incompatibility at line 3 for column "user_id": "not-a-number"
NOTICE:  1 row was skipped due to data type incompatibility
COPY 2
```

It only covers conversion errors in text and CSV format. A line with the wrong number of columns still aborts the load (`extra data after last expected column`), and so does a row that converts fine but breaks a constraint: in our test, an empty `note` in a CSV line (a `NULL` for a `NOT NULL` column) failed with `null value in column "note" … violates not-null constraint` even with `ON_ERROR ignore`, and none of that file's rows were loaded.

## Behind a transaction pooler

Relyt One gives every compute a direct connection string and a pooled one, and the pooled one goes through PgBouncer in transaction mode without prepared statement tracking ([what that breaks in general](/blog/pgbouncer-transaction-pooling)). We repeated the benchmark through a local PgBouncer 1.24.1 set up the same way: `pool_mode = transaction`, `max_prepared_statements = 0`.

With psycopg's default settings, the first method failed straight away:

```
psycopg.errors.DuplicatePreparedStatement: prepared statement "_pg3_0" already exists
```

psycopg prepares a query on the server once it has run it more than `prepare_threshold` times on a connection. Our script had already run `SELECT 1` 20 times on an earlier client connection, so psycopg prepared it as `_pg3_0`. That client disconnected, but the pooler kept its server connection, prepared statement included. The next client got that same server connection, and its own first prepared statement was also named `_pg3_0`. Connecting with `prepare_threshold=None` turns preparing off, and then all seven methods worked through the pooler, `COPY` and pipelined `executemany()` included, and every run delivered exactly 10,000 rows:

```python
conn = psycopg.connect(pooled_url, prepare_threshold=None)
```

It isn't free, and most of the cost comes from turning off prepared statements rather than from the extra hop. Times for 10,000 rows on localhost:

| Method                                | Direct, defaults | Direct, no prepare | PgBouncer, no prepare |
| ------------------------------------- | ---------------- | ------------------ | --------------------- |
| One `INSERT` per row, autocommit      | 1.55 s           | 1.50 s             | 2.17 s                |
| One `INSERT` per row, one transaction | 0.75 s           | 0.94 s             | 1.40 s                |
| `executemany()`                       | 0.090 s          | 0.199 s            | 0.205 s               |
| `INSERT … SELECT FROM unnest(arrays)` | 0.059 s          | 0.059 s            | 0.058 s               |
| `COPY … FROM STDIN`                   | 0.016 s          | 0.016 s            | 0.016 s               |

Without prepared statements, every row-by-row `INSERT` is parsed and planned again, which doubled the pipelined `executemany()`. The hop through the pooler adds time to each round trip, so it shows up in the row-by-row methods. The single-statement methods didn't notice either. One more thing behind the pooler: our `synchronous_commit = off` variant uses a session-level `SET`, which there can land on a different server connection than your `INSERT`s and leak to other clients; use `SET LOCAL` inside a transaction instead.

For a one-off import of a big file, the direct connection is the simpler choice. A long `COPY` holds a server connection for its whole duration, and it doesn't need any of what the pooler is for.

## Which one should you use?

| Situation                                                                | Use                                                      |
| ------------------------------------------------------------------------ | -------------------------------------------------------- |
| Loading a file or a big batch into a table                               | `COPY FROM STDIN` (`\copy` from `psql`)                  |
| Same, but rows may already exist                                         | `COPY` into a staging table, then `INSERT … ON CONFLICT` |
| Batches from application code, needs `ON CONFLICT`, `RETURNING` or joins | `INSERT … SELECT FROM unnest(arrays)`                    |
| Existing code that inserts one row at a time, psycopg 3                  | `executemany()` in one transaction                       |
| A few hundred rows, any driver                                           | Multi-row `VALUES`, at most 65,535 parameters            |
| A big initial load into an empty table                                   | `COPY`, then create indexes, then `ANALYZE`              |

The last row is from the same documentation page: building an index on loaded data is faster than updating it row by row, and a bulk load changes the table's statistics enough that you should run `ANALYZE` afterwards. If you can't change how the client loads data, the single most useful thing is to stop committing per row and, above all, to stop waiting per row.

## Try it on a branch

Every number here came from a laptop, and your schema, row width and region will move them. The way to find out what your own import costs is to run it against a copy of your real database. On Relyt One, a branch starts from its parent's data at a point in time and shares its pages copy-on-write, so you can create one, run the import with two or three of these methods over the real network path, compare, and delete the branch afterwards. The snippets above are all you need: time each one around the same list of rows. Remember `?sslmode=require` in the connection string, and `prepare_threshold=None` if you go through the pooled one.

[Start for free](/auth/signin?ref=blog-postgres-bulk-insert-copy-vs-insert)
