Skip to content

tutorials · tutorial

Save scraped rows to Postgres without duplicates

A Python pattern for idempotent upserts on a natural key, with change tracking, using psycopg.

4 min readPublished 2026-11-25Updated 2026-11-25Reviewed by a person, not a template
Jump to the short answer
On this page
  1. Schema first
  2. The upsert
  3. Why changed_at matters
  4. What breaks next

The short answer

Upsert on a natural key and let Postgres decide whether a row is new. A pipeline that inserts blindly will duplicate every re-run; one that deletes and re-inserts loses history. ON CONFLICT with a real key does neither.

Schema first#

create table if not exists products (
  sku         text primary key,
  title       text not null,
  price       numeric(12,2),
  in_stock    boolean,
  first_seen  timestamptz not null default now(),
  last_seen   timestamptz not null default now(),
  changed_at  timestamptz
);

The upsert#

import psycopg

SQL = """
insert into products (sku, title, price, in_stock)
values (%(sku)s, %(title)s, %(price)s, %(in_stock)s)
on conflict (sku) do update set
  title      = excluded.title,
  price      = excluded.price,
  in_stock   = excluded.in_stock,
  last_seen  = now(),
  changed_at = case when products.price is distinct from excluded.price
                     or products.in_stock is distinct from excluded.in_stock
                    then now() else products.changed_at end
"""

with psycopg.connect(dsn) as conn, conn.cursor() as cur:
    cur.executemany(SQL, rows)
    conn.commit()

Why changed_at matters#

It turns the table into a change feed: `where changed_at > $1` gives you a delta without a separate event stream.

Want this data without building it?

Free 100-row sample with fill rates, then a written quote in 24 hours.

Get a quote

What breaks next#

  • A site with no stable SKU — you will need a composite key and a normaliser
  • Null prices overwriting good ones — guard with COALESCE or skip empty values
  • Timezones: store timestamptz, never local time

Questions this raises

Why not INSERT ... ON CONFLICT DO NOTHING?

Then price changes are never recorded — you keep the first price forever.

Do I need a history table?

Only if you need the full series; changed_at plus a daily snapshot table covers most analysis.

Is executemany fast enough?

For tens of thousands of rows, yes. For millions, use COPY into a staging table and merge.

Scrapefall team

Data engineering — We build and run the extraction pipelines behind every dataset we sell. Guides are written by whoever maintains the source, and reviewed by a second engineer before publishing.

Reviewed by a second engineer before publishing · last updated 2026-11-25

All articles

Send one URL. Get one sample. Decide from data, not a sales call.

100-row sample, masked where needed, with the source URL on every row. Written quote within 24 hours.