Bulk Loading Without Row-by-Row Inserts
Extract 100,000 orders from a PostgreSQL source with a server-side cursor, load them three ways and see why COPY wins, then stream changed rows into a staging table and upsert them in one transaction, and handle a malformed row.
Contentsand lesson path
On this page
- The problem
- Step 1: Create the source and the target
- Step 2: Extract with a server-side cursor
- Step 3: Compare the three loaders
- Step 4: Stage with COPY, then upsert in one transaction
- Step 5: Handle a malformed row
- Check your understanding
- Apply it
- Review prompt
Lessons of ETL/ELT Pipeline Design
- The Data Lifecycle, ETL vs ELT and Ingestion Choices Concept · 25 min
- Lab: A Python Extractor That Survives Flaky APIs Lab · 30 min
- Bulk Loading Without Row-by-Row Inserts Worked example · 20 min
- Incremental Loads with Watermarks and Lookbacks Worked example · 25 min
- Lab: Idempotent Writes and a Safe Backfill Lab · 30 min
- Check: Is This Pipeline Safe to Re-run? Knowledge check · 10 questions
What you will learn
- Extract from REST APIs and databases in Python with pagination, retries with backoff and rate limits, and bulk-load the results (COPY or batched inserts).
Prerequisites: Data Handling, SQL Fundamentals
01. The problem
A shop keeps its orders in an operational PostgreSQL database, shop. Every night a job must copy them into a separate analytics database, analytics, where reports run without slowing down the shop. The first version of the job read each row and ran one INSERT per row. It was fine with a few thousand orders; with millions it ran for hours.
In this worked example you rebuild that job step by step. You will extract rows without loading the whole table into memory, compare three ways of loading them, and then use a pattern that most production loaders follow: bulk-load into a staging table, then merge into the real table in one transaction. You need Docker and a Python virtual environment with psycopg[binary]==3.3.9; the example was tested with PostgreSQL 17.11 (postgres:17-alpine) and Python 3.12.
02. Step 1: Create the source and the target
Start a PostgreSQL container that listens only on your own machine, on port 55432. Both databases live in this one server to keep the example small; in real life they would be different servers. The script setup.sql generates 100,000 orders with generate_series, using arithmetic instead of random numbers so every run produces the same rows. In analytics it creates the target orders table and an unlogged staging table. An unlogged table skips the write-ahead log, so it is faster to fill, but PostgreSQL empties it after a crash. That is acceptable for staging data you can always reload, and wrong for anything you cannot.
-- Two databases in one server: an OLTP-style source and the analytics target.
SET client_min_messages = warning;
DROP DATABASE IF EXISTS shop;
DROP DATABASE IF EXISTS analytics;
CREATE DATABASE shop;
CREATE DATABASE analytics;
\connect shop
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer_id int NOT NULL,
ordered_at timestamptz NOT NULL,
amount numeric(10,2) NOT NULL,
status text NOT NULL
);
INSERT INTO orders
SELECT g,
1 + (g * 7919) % 5000,
timestamptz '2026-10-01 00:00+00' + g * interval '25 seconds',
((g * 37) % 50000) / 100.0,
(ARRAY['paid', 'paid', 'paid', 'refunded'])[1 + g % 4]
FROM generate_series(1, 100000) AS g;
\connect analytics
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer_id int NOT NULL,
ordered_at timestamptz NOT NULL,
amount numeric(10,2) NOT NULL,
status text NOT NULL
);
CREATE UNLOGGED TABLE stage_orders (LIKE orders);
SELECT 'ready' AS status;docker run --name etl-lab -e POSTGRES_PASSWORD=etl-lab \
-p 127.0.0.1:55432:5432 -d postgres:17-alpine
docker exec -i etl-lab psql -U postgres -X -q -v ON_ERROR_STOP=1 < setup.sql
export SOURCE_URL=postgresql://postgres:[email protected]:55432/shop
export TARGET_URL=postgresql://postgres:[email protected]:55432/analytics status
--------
ready
(1 row)03. Step 2: Extract with a server-side cursor
With a normal cursor, cur.execute("SELECT ...") makes the server send the entire result to your program before you read the first row, so a large table can exhaust the memory of the extract machine. A server-side cursor keeps the result on the database server and sends it in batches. In psycopg you get one by giving the cursor a name. Iterating over it fetches itersize rows per network round trip; the default is 100, and the code below raises it to 10,000. The extract() function is a generator, so rows flow into the loader as they arrive.
The same file contains three loaders. load_row_by_row sends one INSERT per row and commits after each one. load_batched sends all the inserts with executemany() in a single transaction; since psycopg 3.1 this uses libpq pipeline mode, which sends many statements without waiting for each reply. load_copy uses COPY ... FROM STDIN: one statement, after which the rows stream to the server as data, not as SQL.
"""Copy orders from the source database into analytics, three different ways."""
import os
import sys
import time
import psycopg
SOURCE = os.environ["SOURCE_URL"] # postgresql://postgres:[email protected]:55432/shop
TARGET = os.environ["TARGET_URL"] # ... /analytics
COLUMNS = "order_id, customer_id, ordered_at, amount, status"
INSERT = f"INSERT INTO orders ({COLUMNS}) VALUES (%s, %s, %s, %s, %s)"
def extract(limit):
"""Stream rows from the source in chunks with a server-side cursor."""
with psycopg.connect(SOURCE) as src:
with src.cursor(name="orders_extract") as cur: # named = server-side
cur.itersize = 10_000 # rows fetched per round trip
cur.execute(f"SELECT {COLUMNS} FROM orders ORDER BY order_id LIMIT %s",
(limit,))
yield from cur
def load_row_by_row(dst, rows):
for row in rows:
dst.execute(INSERT, row)
dst.commit() # one transaction per row
def load_batched(dst, rows):
with dst.cursor() as cur:
cur.executemany(INSERT, rows) # one transaction, sent in a pipeline
dst.commit()
def load_copy(dst, rows):
with dst.cursor() as cur:
with cur.copy(f"COPY orders ({COLUMNS}) FROM STDIN") as copy:
for row in rows:
copy.write_row(row)
dst.commit()
METHODS = {"row": load_row_by_row, "batch": load_batched, "copy": load_copy}
if __name__ == "__main__":
method, limit = sys.argv[1], int(sys.argv[2])
with psycopg.connect(TARGET) as dst:
dst.execute("TRUNCATE orders")
dst.commit()
start = time.perf_counter()
METHODS[method](dst, extract(limit))
seconds = time.perf_counter() - start
loaded = dst.execute("SELECT count(*) FROM orders").fetchone()[0]
print(f"{method:>5}: {loaded:>6} rows in {seconds:6.2f} s"
f" = {loaded / seconds:>7.0f} rows/s")04. Step 3: Compare the three loaders
Run each loader. The row-by-row loader gets only 5,000 rows, because the full table would take minutes. Your numbers will differ from the ones below, which come from one run on a 2012 desktop with the database in Docker on the same machine; what matters is the ratio between them.
python load.py row 5000
python load.py batch 100000
python load.py copy 100000 row: 5000 rows in 6.41 s = 780 rows/s
batch: 100000 rows in 4.49 s = 22251 rows/s
copy: 100000 rows in 0.90 s = 111195 rows/sEach row-by-row insert pays three costs: a network round trip, parsing and planning the statement, and a commit. A commit must wait until the write-ahead log is flushed to disk, so thousands of tiny transactions spend most of their time waiting for the disk. Batching into one transaction removes the per-row commit, and pipeline mode removes most of the waiting for replies. COPY goes further: the statement is parsed once and each row is only decoded and stored. On this machine COPY loaded more than 100 times as many rows per second as the row-by-row loader. Over a real network the gap is usually larger, because every round trip takes longer.
05. Step 4: Stage with COPY, then upsert in one transaction
After the first full load, the nightly job only needs recent orders, and some of them have changed since the last run. Loading them straight into orders would fail on the primary key. Instead, the script below streams the window of rows into stage_orders, then runs one INSERT ... ON CONFLICT statement, often called an upsert. New order_id values are inserted; existing ones are updated, but only when a value really changed, thanks to the WHERE ... IS DISTINCT FROM clause (a comparison that treats two NULLs as equal). Skipping no-op updates avoids writing new row versions for nothing.
The extract side uses COPY (SELECT ...) TO STDOUT, and the chunks go straight into COPY ... FROM STDIN on the target without Python ever parsing a row. The staging fill and the upsert run in one transaction, so a failure part-way leaves orders as it was. The window start is fixed here; the next lesson shows how to choose it with a watermark.
"""Stream changed source rows into staging with COPY, then upsert them in one step."""
import os
import psycopg
SOURCE, TARGET = os.environ["SOURCE_URL"], os.environ["TARGET_URL"]
SINCE = "2026-10-29 00:00+00" # extract window start, fixed for the lab
UPSERT = """
INSERT INTO orders SELECT * FROM stage_orders
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status, amount = EXCLUDED.amount
WHERE (orders.status, orders.amount)
IS DISTINCT FROM (EXCLUDED.status, EXCLUDED.amount)
"""
with psycopg.connect(SOURCE) as src, psycopg.connect(TARGET) as dst:
before = dst.execute("SELECT count(*) FROM orders").fetchone()[0]
dst.execute("TRUNCATE stage_orders")
query = f"COPY (SELECT * FROM orders WHERE ordered_at >= '{SINCE}') TO STDOUT"
with src.cursor().copy(query) as out, \
dst.cursor().copy("COPY stage_orders FROM STDIN") as into:
for chunk in out: # raw COPY data, never parsed in Python
into.write(chunk)
staged = dst.execute("SELECT count(*) FROM stage_orders").fetchone()[0]
changed = dst.execute(UPSERT).rowcount
after = dst.execute("SELECT count(*) FROM orders").fetchone()[0]
dst.commit() # stage + upsert become visible together
inserted = after - before
print(f"staged {staged}, inserted {inserted}, updated {changed - inserted}")-- Two refunds and three new orders arrive in the source.
UPDATE orders SET status = 'refunded' WHERE order_id IN (99990, 99993);
INSERT INTO orders VALUES
(100001, 42, '2026-10-29 22:00+00', 19.99, 'paid'),
(100002, 43, '2026-10-29 22:05+00', 5.00, 'paid'),
(100003, 44, '2026-10-29 22:10+00', 72.50, 'paid');python stage_merge.py
docker exec -i etl-lab psql -U postgres -d shop -X -q < change_source.sql
python stage_merge.py
python stage_merge.pystaged 3233, inserted 0, updated 0
staged 3236, inserted 3, updated 2
staged 3236, inserted 0, updated 0The first run stages 3,233 rows that the full load already holds, so nothing changes. After two refunds and three new orders, the second run inserts 3 rows and updates 2. The third run finds nothing new and changes nothing, so running the job twice is harmless.
06. Step 5: Handle a malformed row
COPY is all or nothing by default: one bad value aborts the whole command and no rows are kept. That is usually the safe choice, because a silent partial load is worse than a loud failure. PostgreSQL 17 added the ON_ERROR ignore option, which skips rows whose values cannot be converted to the column type, and LOG_VERBOSITY verbose, which reports each skipped row. The file below has the letter O instead of a zero in one amount.
"""What COPY does with one malformed row, with and without ON_ERROR (PostgreSQL 17+)."""
import os
import textwrap
import psycopg
CSV = b"""order_id,customer_id,ordered_at,amount,status
200001,7,2026-10-30 08:00+00,12.50,paid
200002,8,2026-10-30 08:01+00,12.5O,paid
200003,9,2026-10-30 08:02+00,30.00,paid
"""
with psycopg.connect(os.environ["TARGET_URL"], autocommit=True) as conn:
conn.add_notice_handler(
lambda n: print(textwrap.fill("NOTICE: " + n.message_primary, 72)))
conn.execute("TRUNCATE stage_orders")
for options in ["FORMAT csv, HEADER true",
"FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose"]:
print(f"-- COPY ... ({options})")
try:
with conn.cursor().copy(f"COPY stage_orders FROM STDIN ({options})") as c:
c.write(CSV)
except psycopg.Error as exc:
print(f"{type(exc).__name__}: {exc.diag.message_primary}")
print(f"CONTEXT: {exc.diag.context}")
staged = conn.execute("SELECT count(*) FROM stage_orders").fetchone()[0]
print("rows in stage:", staged)python bad_copy.py-- COPY ... (FORMAT csv, HEADER true)
InvalidTextRepresentation: invalid input syntax for type numeric: "12.5O"
CONTEXT: COPY stage_orders, line 3, column amount: "12.5O"
rows in stage: 0
-- COPY ... (FORMAT csv, HEADER true, ON_ERROR ignore, LOG_VERBOSITY verbose)
NOTICE: skipping row due to data type incompatibility at line 3 for
column "amount": "12.5O"
NOTICE: 1 row was skipped due to data type incompatibility
rows in stage: 2ON_ERROR ignore covers only type conversion errors. A missing value in a NOT NULL column or a duplicate key still aborts the COPY. If you use it, count the skipped rows and fail the run above a threshold; PostgreSQL 18 adds REJECT_LIMIT for exactly that. Another common design loads every column as text into staging, then validates in SQL and moves bad rows to a quarantine table where someone can inspect them. When you have finished, remove the container with docker rm -f etl-lab, or keep it for the next lesson.
07. Check your understanding
08. Apply it
In the skill practice, your extractor lands API pages as files and an incremental PostgreSQL table holds the result. Load that table with the staging pattern from step 4: COPY the landed rows into an unlogged staging table, reduce them to one row per key, and upsert in one transaction. Log the staged, inserted and updated counts for every run, and make the run fail if more than a small, stated number of rows are rejected.
09. Review prompt
Without looking back, explain: why one INSERT and one commit per row is slow; what a server-side cursor changes; why loaders COPY into staging and then upsert rather than COPY straight into the target; and what ON_ERROR ignore does and does not protect you from.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.