DatabaseMySQL INSERT or REPLACE Commands

MySQL INSERT or REPLACE Commands

In MySQL, the INSERT command is used when we want to insert records into a table. There are instances when this INSERT could fail due to data duplicacy or similar reasons.

The MySQL REPLACE command, when used in this context, helps resolve the data duplicacy problem. When REPLACE is used in place of the INSERT command, it acts as REPLACE when there is data matching the record that you are trying to INSERT, else it just works as INSERT directly.

Here is some example MySQL code illustrating the use of REPLACEand INSERT commands:

CREATE TABLE `STUDENT` (
	`FIRSTNAME` VARCHAR(30) NOT NULL,
	`LASTNAME` VARCHAR(30) NOT NULL,
	PRIMARY KEY (FIRSTNAME, LASTNAME)
);

This results in the following output:

REPLACE INTO STUDENT (FIRSTNAME, LASTNAME) VALUES( 'Steven', 'Fall');
/* Affected rows: 1  Found rows: 0  Warnings: 0  Duration for 1 query: 0.001 sec. */
REPLACE INTO STUDENT (FIRSTNAME, LASTNAME) VALUES( 'Steven', 'Fall');
/* Affected rows: 1  Found rows: 0  Warnings: 0  Duration for 1 query: 0.001 sec. */

Latest Posts

Related Stories