DataFrame.to_sql stops on a row whose primary key is already taken
Fix it fast
Most common cause, 1 of 3The load re-sends rows that the table already holds
Pass a callable as method= that builds the INSERT with a conflict clause.
# PostgreSQL: skip rows whose key exists
from sqlalchemy.dialects.postgresql import insert
def insert_skip_existing(table, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
stmt = insert(table.table).values(data).on_conflict_do_nothing(index_elements=["id"])
return conn.execute(stmt).rowcount
df.to_sql("users", engine, if_exists="append", index=False, method=insert_skip_existing)
# MySQL: update the other columns instead
from sqlalchemy.dialects.mysql import insert as mysql_insert
def upsert(table, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
stmt = mysql_insert(table.table).values(data)
stmt = stmt.on_duplicate_key_update(name=stmt.inserted.name, email=stmt.inserted.email)
return conn.execute(stmt).rowcount
df.to_sql("users", engine, if_exists="append", index=False, method=upsert)Short answer
DataFrame.to_sql with if_exists='append' sends plain INSERT statements, so one key that already exists stops the load with MySQL's 1062 Duplicate entry or PostgreSQL's duplicate key value violates unique constraint. Pass a method= function that adds ON CONFLICT DO NOTHING or ON DUPLICATE KEY UPDATE, drop repeated keys inside the DataFrame, or reload with if_exists='delete_rows' (pandas 3.0+).
Which cause do you have?
Count the colliding keys on both sides before you change anything. Keys that are already in the table point to the first or third cause; keys repeated inside the DataFrame point to the second.
existing = pd.read_sql("SELECT id FROM users", engine)["id"]
print("already in table:", df["id"].isin(existing).sum())
print("repeated in df: ", len(df) - len(df.drop_duplicates(subset=["id"])))Then find the line you see in this list and open its fix:
- 1The load re-sends rows that the table already holds
already in table is above 0, typically after a job was re-run or two runs overlap in time - 2The DataFrame holds the same key more than once
repeated in df is above 0, often after a concat or a merge that multiplied rows - 3A full reload appends on top of the previous run
already in table equals the whole DataFrame, and the job is meant to replace the table's contents each time
What does the error look like?
Duplicate entry '42' for key 'PRIMARY'duplicate key value violates unique constraint "users_pkey"DETAIL: Key (id)=(42) already exists.
Cause 1 of 3
The load re-sends rows that the table already holds
You seealready in table is above 0, typically after a job was re-run or two runs overlap in time
Check
to_sql fails on a duplicate primary key when if_exists='append' meets rows that are already stored. Append only means insert into the existing table: with the default method=None pandas issues one plain INSERT per row, with no rule for conflicts, so the first key that exists makes the database reject the statement.
dup = df[df["id"].isin(existing)]
print(dup.head())Fix
Pass a callable as method= that builds the INSERT with a conflict clause. On PostgreSQL skip existing keys; on MySQL update them. Both patterns come from the pandas to_sql reference.
# PostgreSQL: skip rows whose key exists
from sqlalchemy.dialects.postgresql import insert
def insert_skip_existing(table, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
stmt = insert(table.table).values(data).on_conflict_do_nothing(index_elements=["id"])
return conn.execute(stmt).rowcount
df.to_sql("users", engine, if_exists="append", index=False, method=insert_skip_existing)
# MySQL: update the other columns instead
from sqlalchemy.dialects.mysql import insert as mysql_insert
def upsert(table, conn, keys, data_iter):
data = [dict(zip(keys, row)) for row in data_iter]
stmt = mysql_insert(table.table).values(data)
stmt = stmt.on_duplicate_key_update(name=stmt.inserted.name, email=stmt.inserted.email)
return conn.execute(stmt).rowcount
df.to_sql("users", engine, if_exists="append", index=False, method=upsert)Verify
to_sql returns the number of rows the statement affected and raises nothing; re-running the same load is now harmless.
n = df.to_sql("users", engine, if_exists="append", index=False, method=insert_skip_existing)
print(n) # 0 on a second identical runConfirmed by pandas.pydata.org
Cause 2 of 3
The DataFrame holds the same key more than once
You seerepeated in df is above 0, often after a concat or a merge that multiplied rows
Check
A duplicate-key error from to_sql can come from the DataFrame alone, even when the table is empty. If two rows carry the same id, the second INSERT collides with the first one in the same load, and a conflict clause only hides that the data was wrong.
print(df[df.duplicated(subset=["id"], keep=False)].sort_values("id"))Fix
Decide which copy wins and drop the others before writing. keep='last' keeps the newest row when the frame is in arrival order.
df = df.drop_duplicates(subset=["id"], keep="last")
df.to_sql("users", engine, if_exists="append", index=False)Verify
The first-step count for repeated keys is now 0 and the load completes.
print(len(df) - len(df.drop_duplicates(subset=["id"])))Confirmed by pandas.pydata.org
Cause 3 of 3
A full reload appends on top of the previous run
You seealready in table equals the whole DataFrame, and the job is meant to replace the table's contents each time
Check
When a snapshot job uses append, every run after the first collides with its own earlier output. if_exists='replace' is not a good way out: pandas drops the table first, so keys, indexes and grants you defined outside pandas go with it.
SELECT count(*) FROM users;Fix
On pandas 3.0 or newer, use if_exists='delete_rows': pandas deletes every record in the existing table and then inserts, so the table definition and its primary key stay as they are.
df.to_sql("users", engine, if_exists="delete_rows", index=False)Verify
The row count in the table equals len(df) after each run.
print(len(df), pd.read_sql("SELECT count(*) AS n FROM users", engine)["n"][0])Confirmed by pandas.pydata.org
How do I stop it coming back?
- Give every recurring to_sql call an explicit method= with a conflict clause, so re-running a failed job cannot break on rows it already wrote.
- Make the job check for repeated keys with df.duplicated(subset=[...]).any() right before the write step, and stop with an error when it finds one.
- Pin pandas in requirements; delete_rows needs 3.0 or newer, and pandas 3.x needs Python 3.11 or newer.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine on the same stack: ShopGo, TaxiDex, QistLock.