Skip to content

REPLACE statement

View as Markdown

The REPLACE statement works like INSERT, with one difference: when a new row would duplicate a PRIMARY KEY or UNIQUE value, CoraDB deletes the existing row and inserts the new one instead of returning an error. When there is no conflict, REPLACE simply inserts.

Because the old row is deleted, columns you do not give a value for get their default value, not the value they had before. To change only some columns of an existing row, use INSERT ... ON DUPLICATE KEY UPDATE instead.

REPLACE [INTO] table_name [(column_name, ...)]
{VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...]
REPLACE [INTO] table_name
SET column_name = {expr | DEFAULT} [, column_name = {expr | DEFAULT} ...]
REPLACE [INTO] table_name [(column_name, ...)]
<select_statement>
  • table_name: the table to write to.
  • column_name: the columns that receive values. Without a list, give a value for every column in table order.
  • expr | DEFAULT: the value for each column, or DEFAULT for the column's default value.
  • select_statement: a query whose rows are written to the table.

Make a working copy of three countries:

CREATE TABLE country_copy LIKE countries;
INSERT INTO country_copy SELECT * FROM countries WHERE code IN ('DEU', 'FRA', 'ITA');
SELECT * FROM country_copy ORDER BY code;
code name
DEU Germany
FRA France
ITA Italy

DEU already exists and is replaced; ESP is new and is inserted:

REPLACE INTO country_copy VALUES ('DEU', 'Federal Republic of Germany'), ('ESP', 'Spain');
3 rows affected.

The count includes the deleted row: 2 for DEU (one deleted, one inserted) and 1 for ESP. The SET form works the same way:

REPLACE INTO country_copy SET code = 'ITA', name = 'Italian Republic';
SELECT * FROM country_copy ORDER BY code;
code name
DEU Federal Republic of Germany
ESP Spain
FRA France
ITA Italian Republic

With a query as the source, every returned row either replaces a matching row or is added:

REPLACE INTO country_copy (code, name)
SELECT code, UPPER(name) FROM countries WHERE code IN ('FRA', 'PRT');
SELECT * FROM country_copy ORDER BY code;
code name
DEU Federal Republic of Germany
ESP Spain
FRA FRANCE
ITA Italian Republic
PRT PORTUGAL
  • REPLACE has to look up every new row in the table's primary key and unique indexes. On a table without a primary key or unique index it behaves like INSERT, so use INSERT there.

  • A replaced row is deleted, so foreign keys that reference it are checked as for a DELETE. Cities reference countries, so replacing a country that has cities fails, while ON DUPLICATE KEY UPDATE succeeds:

    REPLACE INTO countries VALUES ('DEU', 'Federal Republic of Germany');
    ERROR: Update/Delete operations are restricted by the foreign key 'fk_city_country_code'.