Chapter 3 — The 01:00 Herd#
Insert 3 or 3,000 rows with one SQL text, one prepared statement and one round trip.
insert_many()UNNEST WITH ORDINALITYin_any() → = ANY($1)on_conflict_do_update()examples/160_bulk_insert_and_upsert.py01:00. The ferry is in. The hill is shaking.
Jumbo: Maya, there are forty of them. They booked through a travel agency. The agency sent a list.
Panda: Simple! A for loop. Forty elephants, forty INSERTs. Then forty SELECTs to check who's already here.
Ferris: Or one statement that carries the whole list. Three elephants or three thousand: same SQL, same single trip.
The mission#
Two jobs before the herd reaches the door:
- Outfit the building. Twelve rooms across three floors need to exist, all together or not at all.
- Import the herd. Insert new guests, look up who's already registered, and refresh the agency's updated profiles without wiping loyalty tiers.
The Panda's plan
Forty elephants means forty statements and forty round trips. The lookup is worse: building
WHERE email IN ($1, $2, …, $40)creates a different SQL text for every list length, so client prepared statements can't be reused across sizes, query logs split across variants, and multi-rowVALUESinserts still create distinct entries inpg_stat_statements.
Ferris: Here's the trick. Instead of forty rows, send PostgreSQL a few arrays: every email, every name, every species. One per column.
1. Outfit twelve rooms in one transaction#
async def outfit_dormitory(pool: pg.Pool) -> Dormitory:
async with pool.transaction() as tx:
dorm = await tx.one(
pg.insert(Dormitory)
.values(
Dormitory(
code="LIS",
name="The Elephant Dormitory — Lisbon",
city="Lisbon",
country="PT",
timezone="Europe/Lisbon",
opened_on=date(2024, 5, 1),
)
)
.returning(Dormitory)
)
rooms = [
Room(
dormitory_id=dorm.dormitory_id,
number=f"{floor}{suffix}",
floor=floor,
category=category,
max_weight_kg=max_weight,
max_guests=max_guests,
)
for floor in (1, 2, 3)
for suffix, category, max_weight, max_guests in FLOOR_LAYOUT
]
created = await tx.all(pg.insert_many(Room, rooms).returning(Room))
print(f"outfitted {len(created)} rooms ({created[0].number}..{created[-1].number})")
# => outfitted 12 rooms (101..304)
return dorm
What just happened
async with pool.transaction() as tx:opens a transaction. Either the dormitory and all twelve rooms exist afterwards, or none of them do. If anything inside the block raises, everything is rolled back.pg.insert_many(Room, rooms)sends all twelve rooms in one statement, and.returning(Room)hands them back in input order, with their newroom_ids.- The list comprehension builds plain
Roomobjects. There's no session to attach them to and nothing to flush. What you build is what gets sent.
2. Import, look up and sync the herd#
async def import_and_sync_herd(pool: pg.Pool) -> None:
# insert_many binds one array per column via UNNEST WITH ORDINALITY, so 3 guests or 3,000
# share one SQL text and one prepared-statement entry in pg_stat_statements.
bulk_insert = pg.insert_many(
Guest,
[
Guest(
email="[email protected]",
first_name="Jumbo",
last_name="Kalahari",
species=Species.SAVANNA,
country="BW",
),
Guest(
email="[email protected]",
first_name="Koko",
last_name="Odzala",
species=Species.FOREST,
country="CG",
loyalty_tier=LoyaltyTier.SILVER,
),
Guest(
email="[email protected]",
first_name="Bram",
last_name="Pleistocene",
species=Species.MAMMOTH,
country="IS",
),
],
)
compiled_bulk = pool.compile(bulk_insert)
inserted = await pool.execute(bulk_insert)
print(f"imported {inserted} guests via UNNEST={'unnest(' in compiled_bulk.sql}")
# => imported 3 guests via UNNEST=True
# = ANY($1) keeps lookup SQL shape constant regardless of list length.
herd_lookup = (
pg.select(Guest)
.where(Guest.email.in_any(["[email protected]", "[email protected]"]))
.order_by(Guest.first_name.asc())
)
compiled_lookup = pool.compile(herd_lookup)
guests = await pool.all(herd_lookup)
print(f"matched {[g.first_name for g in guests]} via ANY={'ANY($1)' in compiled_lookup.sql}")
# => matched ['Bram', 'Jumbo'] via ANY=True
# Travel agency sends refreshed profiles: update changed fields, preserve loyalty state.
synced = await pool.all(
pg.insert_many(
Guest,
[
Guest(
email="[email protected]",
first_name="Koko",
last_name="Odzala-Mbomo",
species=Species.FOREST,
country="CG",
phone="+242 06 555 010",
),
Guest(
email="[email protected]",
first_name="Pip",
last_name="Kinabatangan",
species=Species.PYGMY,
country="MY",
),
],
)
.on_conflict_do_update(
Guest.email,
by_name=True,
exclude=(Guest.loyalty_tier, Guest.peanut_points),
)
.returning(Guest)
)
for g in synced:
print(f"synced {g.full_name} [{g.loyalty_tier.name}] phone={g.phone}")
# => synced Koko Odzala-Mbomo [SILVER] phone=+242 06 555 010
# => synced Pip Kinabatangan [CALF] phone=None
What just happened
insert_manycompiled toINSERT … SELECT … FROM unnest($1, $2, …) WITH ORDINALITY … ORDER BY u.ord. Each parameter is one array per column, andWITH ORDINALITYkeeps the rows in your order. The example printsUNNEST=Truebecause it checks the compiled SQL.Guest.email.in_any([...])always compiles to= ANY($1)with a single array parameter. Two emails or two hundred, the SQL text never changes..on_conflict_do_update(Guest.email, by_name=True, exclude=(Guest.loyalty_tier, Guest.peanut_points))is an upsert:by_name=Trueupdates every writable column present in theINSERTfromEXCLUDED, automatically skipping omitted SQL defaults likepublic_id(uuidv7()), generated columns, and the excluded loyalty fields. Koko keeps herSILVERtier while her name and phone refresh; Pip is new, so she's inserted. (When you only want to touch one or two columns, passupdate_cols=(...)for a tiny allowlist.)
Here's the upsert exactly as PostgreSQL received it, captured during the last test run:
-- captured live from PostgreSQL · examples/__wire__/bulk_insert_and_upsert.sql
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
ON CONFLICT ("email") DO UPDATE SET
"first_name" = EXCLUDED."first_name",
"last_name" = EXCLUDED."last_name",
"species" = EXCLUDED."species",
"phone" = EXCLUDED."phone",
"country" = EXCLUDED."country",
"birth_date" = EXCLUDED."birth_date",
"preferences" = EXCLUDED."preferences",
"marketing_opt_in" = EXCLUDED."marketing_opt_in"
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
Ferris' basement: one SQL text, forever
One SQL text means one client-side prepared statement and one cached plan per query, so PostgreSQL runs Parse once regardless of list or batch length. (modern PostgreSQL also squashes variable IN lists inside pg_stat_statements; pgdorm gives you the same shape stability at the wire protocol level, in query logs, and for bulk UNNEST inserts too — which IN-list squashing doesn't cover.) This is a house rule of pgdorm: no variable-length IN (…) lists, ever.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 7 statements in 6 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/bulk_insert_and_upsert.sql
-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row
-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
($1, $2, $3, $4, $5, $6, $7, $8),
($9, $10, $11, $12, $13, $14, $15, $16),
($17, $18, $19, $20, $21, $22, $23, $24),
($25, $26, $27, $28, $29, $30, $31, $32),
($33, $34, $35, $36, $37, $38, $39, $40),
($41, $42, $43, $44, $45, $46, $47, $48),
($49, $50, $51, $52, $53, $54, $55, $56),
($57, $58, $59, $60, $61, $62, $63, $64),
($65, $66, $67, $68, $69, $70, $71, $72),
($73, $74, $75, $76, $77, $78, $79, $80),
($81, $82, $83, $84, $85, $86, $87, $88),
($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows
-- ── round trip 3 ──
COMMIT;
-- ── round trip 4 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord;
-- → 3 affected
-- ── round trip 5 ──
SELECT
"guest_id",
"public_id",
"email",
"first_name",
"last_name",
"full_name",
"species",
"phone",
"country",
"birth_date",
"loyalty_tier",
"peanut_points",
"preferences",
"marketing_opt_in",
"created_at"
FROM "guest"
WHERE "email" = ANY($1)
ORDER BY "first_name" ASC;
-- → 2 rows
-- ── round trip 6 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
ON CONFLICT ("email") DO UPDATE SET
"first_name" = EXCLUDED."first_name",
"last_name" = EXCLUDED."last_name",
"species" = EXCLUDED."species",
"phone" = EXCLUDED."phone",
"country" = EXCLUDED."country",
"birth_date" = EXCLUDED."birth_date",
"preferences" = EXCLUDED."preferences",
"marketing_opt_in" = EXCLUDED."marketing_opt_in"
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 2 rows
Shift report
- Grouped writes in a transaction that's all-or-nothing
- Inserted many rows with one statement and got them back in order
- Looked up a list with
= ANY($1)instead ofIN (…) - Upserted with
ON CONFLICT DO UPDATE, choosing exactly which columns change
Try it yourself
Double the herd: copy the three Guest(...) entries in import_and_sync_herd with new emails and run the script again. Compare the SQL in the wire transcript before and after. What changed?
Go deeper: tests/integration/crud/test_quickstart.py (live PostgreSQL test suites & snapshots)
Note
Also in pgdorm: Need to insert rows directly from another query (INSERT INTO ... SELECT ...)? Use Insert.from_select(...) — see the Queries & DML Reference.
Sticky note from Management
"The mammoth typed his email in CAPITALS with spaces. Twice. Also he wants a glacier-foam pillow. FIX THE KIOSK."
← PreviousChapter 2 · Partial Updates & GuardrailsChapter 2 · Partial PATCH & Guardrails
Next →Chapter 4 · A Mammoth at the KioskChapter 4 · TypeTable, JSONB & UUIDv7