The difference between insert into and replace into and insert ignore in MySQL

Source: Internet
Author: User

Three commonly used statements for inserting data in MySQL:


Insert into indicates the data is inserted, the database will check the primary key (PrimaryKey), if there is a repeat error;


Replace into represents inserting replacement data, PrimaryKey in the requirements table, or a unique index, if the database already has data, replace with new data, and insert into if no data effects are present;

The Replace statement returns a number that indicates the number of rows affected. The number is the number of rows that are deleted and inserted. If the number is 1 for a single-line replace, the row is inserted and no rows are deleted. If the number is greater than 1, one or more old rows are deleted before the new row is inserted. If the table contains more than one unique index, and the new row replicates the values of the different old rows in different unique indexes, it is possible that a single row has replaced multiple old rows.


Insert Ignore indicates that if the same record already exists, the current new data is ignored;

Note: These are all based on the primary key ...
The following are the differences between code descriptions, as follows:
CREATE TABLE TESTTB (
ID int NOT NULL PRIMARY key,
name varchar,
Age int
);
INSERT INTO TESTTB (id,name,age) VALUES (1, BB);
select * from TESTTB;
Insert Ignore into TESTTB (Id,name,age) VALUES (1, "AA");
SELECT * from testtb;//is still 1, "BB", 13, because ID is primary key, duplicate primary key but use ignore error is ignored
Replace into TESTTB (id,name,age) VALUES (1, "AA", n);
select * from TESTTB;//Data changed to 1, "AA",

The difference between insert into and replace into and insert ignore in MySQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.