DatabaseMySQL INSERT or REPLACE Commands

MySQL INSERT or REPLACE Commands

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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. */

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories