@@ -2788,7 +2788,7 @@ def to_sql(
27882788 con ,
27892789 * ,
27902790 schema : str | None = None ,
2791- if_exists : Literal ["fail" , "replace" , "append" ] = "fail" ,
2791+ if_exists : Literal ["fail" , "replace" , "append" , "delete_rows" ] = "fail" ,
27922792 index : bool = True ,
27932793 index_label : IndexLabel | None = None ,
27942794 chunksize : int | None = None ,
@@ -2825,12 +2825,13 @@ def to_sql(
28252825 schema : str, optional
28262826 Specify the schema (if database flavor supports this). If None, use
28272827 default schema.
2828- if_exists : {'fail', 'replace', 'append'}, default 'fail'
2828+ if_exists : {'fail', 'replace', 'append', 'delete_rows' }, default 'fail'
28292829 How to behave if the table already exists.
28302830
28312831 * fail: Raise a ValueError.
28322832 * replace: Drop the table before inserting new values.
28332833 * append: Insert new values to the existing table.
2834+ * delete_rows: If a table exists, delete all records and insert data.
28342835
28352836 index : bool, default True
28362837 Write DataFrame index as a column. Uses `index_label` as the column
@@ -2900,6 +2901,7 @@ def to_sql(
29002901 --------
29012902 Create an in-memory SQLite database.
29022903
2904+ >>> import pandas as pd
29032905 >>> from sqlalchemy import create_engine
29042906 >>> engine = create_engine('sqlite://', echo=False)
29052907
@@ -2933,7 +2935,7 @@ def to_sql(
29332935 >>> df2.to_sql(name='users', con=engine, if_exists='append')
29342936 2
29352937 >>> with engine.connect() as conn:
2936- ... conn.execute(text("SELECT * FROM users")).fetchall()
2938+ ... conn.execute(text("SELECT * FROM users")).fetchall() # doctest: +NORMALIZE_WHITESPACE
29372939 [(0, 'User 1'), (1, 'User 2'), (2, 'User 3'),
29382940 (0, 'User 4'), (1, 'User 5'), (0, 'User 6'),
29392941 (1, 'User 7')]
@@ -2947,6 +2949,16 @@ def to_sql(
29472949 ... conn.execute(text("SELECT * FROM users")).fetchall()
29482950 [(0, 'User 6'), (1, 'User 7')]
29492951
2952+ Delete all rows before inserting new records with ``df3``
2953+
2954+ >>> df3 = pd.DataFrame({"name": ['User 8', 'User 9']})
2955+ >>> df3.to_sql(name='users', con=engine, if_exists='delete_rows',
2956+ ... index_label='id')
2957+ 2
2958+ >>> with engine.connect() as conn:
2959+ ... conn.execute(text("SELECT * FROM users")).fetchall()
2960+ [(0, 'User 8'), (1, 'User 9')]
2961+
29502962 Use ``method`` to define a callable insertion method to do nothing
29512963 if there's a primary key conflict on a table in a PostgreSQL database.
29522964
0 commit comments