REPLACE statement
REPLACE as delete-then-insert on a key clash, with the privileges and triggers it involves.
REPLACE works like INSERT, except that when a new row clashes with an existing row on a primary or unique key, the old row is deleted first and then the new row is inserted.
Syntax#
REPLACE [INTO] [db_name.]tbl_name [(col_name [, col_name] ...)]
{ { VALUES | VALUE } (value_list) [, (value_list)] ...
| query_expression }
[RETURNING select_item [, select_item] ...]
REPLACE [INTO] [db_name.]tbl_name
SET col_name = value [, col_name = value] ...
[RETURNING select_item [, select_item] ...]Arguments#
The arguments are those of INSERT. IGNORE is read after the keyword but has no meaning for REPLACE.
Remarks#
- A clash on a key deletes the row in the way, then inserts.
- Triggers: the row in the way is a delete (
BEFORE/AFTER DELETErun), then the insert (BEFORE/AFTER INSERT). - Foreign keys: the delete follows the
ON DELETEaction of the referring keys. CHECKconstraints and generated columns are applied to the new row.- Privileges:
INSERTandDELETEon the table (MySQL asks for both). REPLACE ... RETURNINGis MariaDB's form; the parser does not test the dialect; it is checked against MariaDB.- Inside a transaction a rolled-back
REPLACEputs the deleted row back.
Examples#
Example:
REPLACE INTO t (id, name, qty) VALUES (1, 'a', 100) RETURNING id, name, qty;
REPLACE INTO t VALUES (1, -9, 1, 'ab'); -- error 3819 if a CHECK refuses the new row