The REPLACE
statement in MySQL is used to insert or update a record into a table. If the record already exists in the table, it will be replaced by the new record, otherwise a new record will be inserted.
The REPLACE
statement works in a similar way to the INSERT INTO
statement. The syntax of the REPLACE
statement is as follows:
REPLACE INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
In this syntax, table_name
is the name of the table where you want to insert or update the record, and (column1, column2, column3, ...)
is a comma-separated list of the columns that you want to insert data into.
The VALUES
clause is used to specify the values that you want to insert into the table. If a record with the same primary key or unique index as the new record already exists, the existing record will be deleted and replaced with the new record. If no record with the same primary key or unique index as the new record exists, a new record will be inserted.
For example, let’s assume that we have a table named employees
with columns id
, name
, age
, and salary
. We can use the REPLACE
statement to insert or update a record in the table as follows:
REPLACE INTO employees (id, name, age, salary) VALUES (1, 'John', 30, 5000);
If there is already a record in the employees
table with id
equal to 1
, that record will be updated with the new values of name
, age
, and salary
. Otherwise, a new record will be inserted with the specified values.