SQLite REPLACE vs UPSERT: IDs, Defaults and Foreign Keys
Compare SQLite INSERT OR REPLACE with ON CONFLICT DO UPDATE using a tested lab for row IDs, defaults, cascading deletes, RESTRICT and audit triggers.
INSERT OR REPLACE can delete conflicting rows and insert new data, resetting omitted values and triggering foreign-key actions. ON CONFLICT DO UPDATE changes the selected existing row through an explicit assignment list. Reusing the same primary-key value does not turn REPLACE into an update.
The parent row still exists, but its detail rows disappeared
An application saves a product using INSERT OR REPLACE. The product still appears in the catalog, yet its related detail records are gone and an omitted quantity has returned to zero. Looking only at the final parent row makes the operation resemble an update. Looking at the dependent rows reveals a different operation.
This guide compares replacement with a targeted ON CONFLICT DO UPDATE using an original in-memory lab. It checks an omitted primary key, an explicitly reused primary key, column defaults, foreign-key actions and delete-trigger visibility. The examples use SQLite syntax; do not transfer their behavior to a different database merely because it has a similarly named command.
The practical question is whether an existing entity should retain its identity and relationships while selected attributes change. When that is the requirement, write an explicit update policy and test its effects. A command that finishes successfully is not enough evidence that it preserved the business entity you intended.
Replacement and a conflict-targeted update express different policies
For a uniqueness collision, REPLACE removes the conflicting existing row before the new insert succeeds. The fixture makes that visible by attaching a child with ON DELETE CASCADE and by giving the original parent values that are not included in the replacement statement. Neither the child nor those omitted values can be inferred from the replacement payload.
A targeted UPSERT identifies the uniqueness condition that selects the existing row, then assigns the columns listed in DO UPDATE. In the example, sku identifies the product and only title is changed. excluded.title supplies the incoming title. The statement deliberately leaves id, note and qty out of the update assignments.
This is not a promise that every UPSERT preserves every key. If your DO UPDATE assigns a primary key, relationship consequences must be considered again. Choose the assignments according to the entity contract; the syntax does not decide that contract for you.
-- These statements assume the item schema in the complete lab below.
INSERT OR REPLACE INTO item(sku, title)
VALUES ('A', 'Changed');
INSERT INTO item(sku, title)
VALUES ('A', 'Changed')
ON CONFLICT(sku) DO UPDATE SET title = excluded.title;Source: SQLite UPSERT: targets, excluded values and DO UPDATE limitations ↗
Compare complete outcomes from a fresh starting state
Every row in this table starts with product A at id 41, note keep, quantity 7 and one child row. Another product at id 99 remains present, which makes the generated ID in this controlled replacement fixture 100. The table reports observed outcomes from this schema; it does not claim that replacement always produces a different numeric ID.
The same-ID case is the important counterexample. Explicitly inserting id 41 again still deletes the old parent under replacement semantics. The child is removed by CASCADE even though the final parent has the familiar number. Identity-sensitive behavior cannot be established by comparing the final key alone.
| Operation on existing A | Final id | Final note / qty | Child outcome |
|---|---|---|---|
| REPLACE, omit id | 100 | new / 0 | Deleted by CASCADE |
| REPLACE, explicitly reuse id 41 | 41 | new / 0 | Deleted by CASCADE |
| UPSERT, update only title | 41 | keep / 7 | Preserved |
| Same-id REPLACE with RESTRICT | 41, original row unchanged | keep / 7 | Statement rejected; child preserved |
| Same UPSERT with RESTRICT | 41 | keep / 7 | Preserved |
Source: SQLite conflict resolution and REPLACE deletion behavior ↗
An omitted insert value is not an instruction to preserve an old value
The item schema gives note a default of new and qty a default of zero. A replacement statement that supplies only sku and title inserts those defaults. It does not merge the old note and quantity into the new row. Treat omitted fields in a replacement payload as insert inputs, not as partial-update instructions.
The UPSERT has two paths. When sku A already exists, its update list changes only title and retains the other existing values. When sku C is new, the same statement performs an ordinary insert, so the omitted columns receive their defaults. The lab checks both paths to prevent the misleading claim that UPSERT always preserves omitted fields.
A migration from replacement to UPSERT therefore needs an insertion policy as well as an update policy. Decide what a new row should contain, which fields an existing row may change, and whether missing incoming values mean preserve, clear or reject. Those choices belong in explicit SQL and input validation.
Foreign-key actions and delete audit triggers are separate observations
With foreign-key enforcement enabled, ON DELETE CASCADE removes children when replacement deletes the parent. Switching to ON DELETE RESTRICT instead rejects a replacement that would delete a parent with a child. Reusing the parent key in the attempted new row does not avoid that immediate restriction in this fixture.
The lab also toggles recursive_triggers. With it off, the replacement deletion is absent from the parent DELETE audit trigger, while the cascade still removes the child. With it on, the parent deletion is recorded. An empty application audit table is therefore not sufficient proof that no deletion occurred.
Query the connection settings instead of relying on a remembered default. The fixture enables foreign_keys and reads it back before inserting data; it also sets and reads recursive_triggers for every independent case. Existing foreign-key setup and transaction-scoping guidance is linked below rather than repeated as a replacement-specific repair.
Run the complete row, relationship and trigger experiment
Save this block as replace_upsert_lab.py and run python replace_upsert_lab.py. It creates only disposable in-memory databases and closes each connection after its case. Each comparison starts from fresh rows. No production file is opened, modified or used as a test fixture.
The published code ran on Python 3.12.14 with SQLite 3.53.1 and completed 52 checks. It verifies settings, full selected parent state, child state, audit events and relationship consistency; it also checks a rejected update and a two-constraint replacement. Your Python runtime may link a different SQLite version, so retain the printed engine version when comparing results.
The connection uses isolation_level=None to keep this small experiment in SQLite autocommit mode outside an explicit transaction. Its single-statement failures are inspected immediately. This is a behavior fixture, not a transaction framework, concurrency benchmark or audit design for a deployed application.
The SQL strings interpolated into schema setup come only from the lab’s CASCADE/RESTRICT choice and integer trigger flag. Application data should use bound parameters. Keep dynamic SQL identifiers and policy fragments under explicit control rather than substituting untrusted input into SQL text.
import sqlite3
checks = 0
def expect(actual, expected):
global checks
assert actual == expected, (actual, expected)
checks += 1
def database(recursive=0, action="CASCADE"):
assert action in ("CASCADE", "RESTRICT")
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("PRAGMA foreign_keys = ON")
db.execute(f"PRAGMA recursive_triggers = {int(bool(recursive))}")
expect(db.execute("PRAGMA foreign_keys").fetchone(), (1,))
expect(db.execute("PRAGMA recursive_triggers").fetchone(), (recursive,))
db.executescript(f"""
CREATE TABLE item(
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
note TEXT NOT NULL DEFAULT 'new',
qty INTEGER NOT NULL DEFAULT 0 CHECK(qty >= 0)
);
CREATE TABLE detail(
id INTEGER PRIMARY KEY,
item_id INTEGER NOT NULL REFERENCES item(id) ON DELETE {action}
);
CREATE TABLE audit(kind TEXT, item_id INTEGER);
CREATE TRIGGER item_deleted AFTER DELETE ON item BEGIN
INSERT INTO audit VALUES('delete', OLD.id);
END;
CREATE TRIGGER item_updated AFTER UPDATE ON item BEGIN
INSERT INTO audit VALUES('update', OLD.id);
END;
INSERT INTO item VALUES(41, 'A', 'Original', 'keep', 7);
INSERT INTO item VALUES(99, 'B', 'Other', 'other', 1);
INSERT INTO detail VALUES(1, 41);
""")
return db
replace_new = "INSERT OR REPLACE INTO item(sku,title) VALUES('A','Changed')"
replace_same = "INSERT OR REPLACE INTO item(id,sku,title) VALUES(41,'A','Changed')"
upsert = """
INSERT INTO item(sku,title) VALUES('A','Changed')
ON CONFLICT(sku) DO UPDATE SET title=excluded.title
"""
cases = [
(replace_new, 0, "CASCADE", (100, 'Changed', 'new', 0), [], []),
(replace_same, 0, "CASCADE", (41, 'Changed', 'new', 0), [], []),
(upsert, 0, "CASCADE", (41, 'Changed', 'keep', 7), [(1,41)], [('update',41)]),
(replace_new, 1, "CASCADE", (100, 'Changed', 'new', 0), [], [('delete',41)]),
(replace_same, 1, "CASCADE", (41, 'Changed', 'new', 0), [], [('delete',41)]),
(upsert, 0, "RESTRICT", (41, 'Changed', 'keep', 7), [(1,41)], [('update',41)]),
]
for sql, recursive, action, parent, details, audit in cases:
db = database(recursive, action)
try:
db.execute(sql)
expect(db.execute("SELECT id,title,note,qty FROM item WHERE sku='A'").fetchone(), parent)
expect(db.execute("SELECT id,item_id FROM detail ORDER BY id").fetchall(), details)
expect(db.execute("SELECT kind,item_id FROM audit ORDER BY rowid").fetchall(), audit)
expect(db.execute("PRAGMA foreign_key_check").fetchall(), [])
finally:
db.close()
# The no-conflict UPSERT branch is an ordinary insert with defaults.
db = database()
try:
db.execute("""
INSERT INTO item(sku,title) VALUES('C','Brand new')
ON CONFLICT(sku) DO UPDATE SET title=excluded.title
""")
expect(db.execute("SELECT title,note,qty FROM item WHERE sku='C'").fetchone(),
('Brand new', 'new', 0))
expect(db.execute("SELECT id,item_id FROM detail").fetchall(), [(1,41)])
finally:
db.close()
# RESTRICT rejects even a replacement that proposes the same primary key.
db = database(action="RESTRICT")
try:
failed = False
try:
db.execute(replace_same)
except sqlite3.IntegrityError:
failed = True
expect(failed, True)
expect(db.execute("SELECT id,title,note,qty FROM item WHERE sku='A'").fetchone(),
(41, 'Original', 'keep', 7))
expect(db.execute("SELECT id,item_id FROM detail").fetchall(), [(1,41)])
finally:
db.close()
# A failing DO UPDATE is not made valid by the uniqueness handler.
db = database()
try:
failed = False
try:
db.execute("""
INSERT INTO item(sku,title) VALUES('A','Changed')
ON CONFLICT(sku) DO UPDATE SET qty=-1
""")
except sqlite3.IntegrityError:
failed = True
expect(failed, True)
expect(db.execute("SELECT title,qty FROM item WHERE sku='A'").fetchone(), ('Original',7))
expect(db.execute("SELECT * FROM audit").fetchall(), [])
finally:
db.close()
# Two different uniqueness conflicts can remove two different rows.
db = sqlite3.connect(":memory:", isolation_level=None)
try:
db.executescript("""
CREATE TABLE account(id INTEGER PRIMARY KEY, code TEXT UNIQUE, email TEXT UNIQUE);
INSERT INTO account VALUES(1,'a','x@example.invalid');
INSERT INTO account VALUES(2,'b','y@example.invalid');
INSERT OR REPLACE INTO account(code,email) VALUES('a','y@example.invalid');
""")
expect(db.execute("SELECT code,email FROM account").fetchall(), [('a','y@example.invalid')])
expect(db.execute("SELECT count(*) FROM account WHERE id IN (1,2)").fetchone(), (0,))
finally:
db.close()
print(f"PASS: {checks} checks; SQLite {sqlite3.sqlite_version}")A uniqueness handler does not make every invalid value acceptable
The CHECK(qty >= 0) constraint remains relevant. The lab attempts an UPSERT whose DO UPDATE assigns -1, catches the resulting integrity error and confirms that the original title and quantity remain unchanged. There is no successful partial update in that single-statement fixture.
An ON CONFLICT target is not a general exception handler for foreign keys, CHECK constraints or every other error. If the update branch violates a constraint, DO UPDATE uses ABORT behavior. Distinguish a failed statement from a deliberately skipped update or an accepted replacement when reporting import results.
If an import groups several statements into one business action, decide its transaction boundary separately. An error on the current statement does not establish that earlier statements in your transaction were undone. Preserve the error context and use the application’s transaction owner to choose rollback, retry or rejection.
Source: SQLite UPSERT: targets, excluded values and DO UPDATE limitations ↗
A replacement can conflict with more than one existing row
The account fixture has two uniqueness rules: code and email. The incoming row takes code a from the first existing row and the email from the second. REPLACE resolves both collisions by removing both existing rows and inserting one incoming row. Checking only the constraint you had in mind would miss half of the effect.
The complete Python lab executes the SQL below and verifies that neither original ID remains. This is another reason to inspect every unique index before choosing replacement. A targeted UPSERT makes the selected matching rule explicit, but the resulting update still has to satisfy other constraints; it is not a way to merge arbitrary conflicting entities automatically.
If an external identifier and an email point at different accounts, treat that as an identity-resolution decision. Do not use replacement simply because it makes an insert return without a uniqueness error. The application needs a policy for which entity is authoritative and which relationships may be retained.
-- Independent disposable example; do not run against an existing account table.
CREATE TABLE account(
id INTEGER PRIMARY KEY,
code TEXT UNIQUE,
email TEXT UNIQUE
);
INSERT INTO account VALUES(1, 'a', 'x@example.invalid');
INSERT INTO account VALUES(2, 'b', 'y@example.invalid');
INSERT OR REPLACE INTO account(code, email)
VALUES('a', 'y@example.invalid');
SELECT id, code, email FROM account;Source: SQLite conflict resolution and REPLACE deletion behavior ↗
Verify a change from REPLACE using the entity contract
Before changing a real write path, inspect the exact SQL generated by the application or ORM, the matching unique index, omitted insert fields, foreign-key actions and triggers. Reproduce the affected schema and a small set of representative relationships in a disposable test. Avoid assuming that a method called save or upsert necessarily generates the SQL you expect.
Compare both successful and rejected writes. Check the parent key, untouched attributes, child membership and observable audit events, not just the updated title. Include a genuinely new key so the ordinary insertion path is tested as well. If multiple uniqueness rules can disagree, include that conflict explicitly.
For an existing entity whose identity and children should remain, a narrow DO UPDATE list is a clearer expression of the intended change than replacement. When replacement is truly the desired delete-and-insert policy, document its effects and test them deliberately. The choice should follow the data relationship contract, not the shortest statement.
Your next steps
- Choose whether the operation should retain an existing entity or deliberately replace it.
- Test omitted columns, child rows and all unique constraints; final parent values alone hide important effects.
- Verify foreign-key and trigger settings, and handle statement failure separately from transaction rollback.
Sources & official resources
Linked resources checked on 2026-11-06. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →