REPLACE
TheREPLACE statement inserts a row into a table. If the row violates a UNIQUE or PRIMARY KEY constraint, the existing conflicting row is deleted before the new row is inserted.
Syntax
Description
REPLACE is equivalent to INSERT OR REPLACE. When a REPLACE inserts a row that would violate a UNIQUE or PRIMARY KEY constraint, it deletes the existing row that causes the conflict, then inserts the new row. If no constraint violation occurs, REPLACE behaves identically to INSERT.
How REPLACE Differs from INSERT
With a plainINSERT, a constraint violation causes the statement to fail with an error. With REPLACE, the conflicting row is silently deleted and the new row takes its place.
Because the conflicting row is deleted first, REPLACE may fire DELETE triggers on the old row and INSERT triggers on the new row.
REPLACE deletes the entire conflicting row and inserts a new one. This means any columns not specified in the REPLACE statement receive their default values, not the values from the deleted row. If you want to keep existing column values while updating specific columns, use INSERT … ON CONFLICT DO UPDATE instead.Constraint Behavior
When multipleUNIQUE constraints exist on a table, REPLACE deletes every row that conflicts with the new row before inserting it. This can result in more than one row being deleted by a single REPLACE operation.
If a NOT NULL constraint is violated on a column that has no DEFAULT value, the REPLACE fails with an error.
Examples
Basic REPLACE
REPLACE deletes and re-inserts
UnlikeUPDATE, REPLACE removes the old row entirely. Columns not specified in the statement receive their default values:
Multi-row REPLACE
See Also
- INSERT for adding rows without conflict resolution
- INSERT … ON CONFLICT for conditional insert-or-update with control over which columns are updated
- UPDATE for modifying existing rows in place