AI Hints
Home›PostgreSQL Tutorial›COPY, Pools and a Python Report
PostgreSQL · Lesson 85 of 120

COPY and Bulk Loading

The fast way in.

⏱ 2 min read▶ Video at 1:16:39🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Inserting a hundred thousand rows one at a time is slow. Copy streams many rows in one go, and it's the fastest way to load data into Postgres.

  • One by one: slow
  • COPY streams
  • Fastest

Copy rows in from Python

We create a table for page views. Cursor copy opens a copy stream. Write row sends each row, and they all go in as one fast operation. Run it. A hundred thousand rows, loaded in well under a second.

load.pypython
import psycopg

conn = psycopg.connect("postgresql://postgres:postgres@localhost:5432/riverside")
import time

conn.execute("CREATE TABLE views (book_id int, ms int)")
start = time.perf_counter()
with conn.cursor().copy("COPY views (book_id, ms) FROM STDIN") as copy:
    for i in range(100_000):
        copy.write_row((i % 30 + 1, i % 900))
conn.commit()
secs = time.perf_counter() - start
n = conn.execute("SELECT count(*) FROM views").fetchone()[0]
print(n, "rows,", "under a second" if secs < 1 else "slow")
Output
100000 rows, under a second

Ways to load

Copy from standard in, from Python, is the fastest. Backslash copy in psql loads a CSV file from your computer. Execute many is fine for hundreds of rows. And always load first, then add indexes.

keyvalue
COPY ... FROM STDINfastest
\copy in psqlCSV files
executemanysmall batches
Indexesafter loading

Summary

Copy streams rows into Postgres far faster than single inserts. Next, connection pools.

Key takeaways
  • COPY
  • write_row
  • Fast
Next up: Connection Pools — reuse connections