What is the difference between insert into, replace into, and insert ignore in MYSQL? mysqlignore

Source: Internet
Author: User

What is the difference between insert into, replace into, and insert ignore in MYSQL? mysqlignore

The following statements are commonly used in mysql to insert data:


Insert into indicates that the data is inserted. The database checks the primary key (PrimaryKey). If there is a duplicate, an error is returned;


Replace into indicates insertion and replacement of data. If the table requires a PrimaryKey or unique index, if the database already has data, replace it with new data. If there is no data effect, it is the same as insert;

The REPLACE statement returns a number to indicate the number of affected rows. This is the sum of the number of deleted and inserted rows. If this number is 1 for a single row, one row is inserted and no row is 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 multiple unique indexes, and the new row copies the values of different old rows in different unique indexes, it is possible that a single row replaces 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 code describes the differences between them:
Create table testtb (
Id int not null primary key,
Name varchar (50 ),
Age int
);
Insert into testtb (id, name, age) values (1, "bb", 13 );
Select * from testtb;
Insert ignore into testtb (id, name, age) values (1, "aa", 13 );
Select * from testtb; // It is still 1, "bb", 13. Because id is the primary key, the primary key is repeated, but ignore is used, the error is ignored.
Replace into testtb (id, name, age) values (1, "aa", 12 );
Select * from testtb; // The data is changed to 1, "aa", 12

Related Article

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.