Skip to content
TodayTell Data

Save scraped rows to Postgres without duplicates

Updated 2026-11-25 · 4 min read · By BYM Data team

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, 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

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.

BYM Data 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.

Get a free sampleWhatsApp