SQL reference (MySQL and MariaDB dialects)

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#

SQL
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 DELETE run), then the insert (BEFORE/AFTER INSERT).
  • Foreign keys: the delete follows the ON DELETE action of the referring keys.
  • CHECK constraints and generated columns are applied to the new row.
  • Privileges: INSERT and DELETE on the table (MySQL asks for both).
  • REPLACE ... RETURNING is MariaDB's form; the parser does not test the dialect; it is checked against MariaDB.
  • Inside a transaction a rolled-back REPLACE puts the deleted row back.

Examples#

Example:

SQL
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

See also#