6

I have the following table (tbl_test) in MySQL server:

id    AUTO_INCRECMENT  PRIMARY
text1 VARCHAR(20)

and inserted a row of data:

INSERT INTO tbl_test (text1) VALUES ('Apple')

id    text1
===========
1     Apple

Then, I plan to use REPLACE INTO to check for existing value and insert if needed:

REPLACE INTO tbl_test (text1) VALUES ('Apple')

But it inserted a new row.

id    text1
===========
1     Apple
2     Apple

How can I check for existing data and insert only if needed (ignoring auto increment primary key)?

2
  • Can you use unique index on column? Commented Feb 3, 2015 at 10:10
  • I can use it on the columns. Commented Feb 3, 2015 at 10:17

2 Answers 2

8

You can make use of UPSERT

INSERT INTO tbl_test
(`text1`)
VALUES( 'Apple')
ON DUPLICATE KEY UPDATE
`text1` = VALUES(text1);
Sign up to request clarification or add additional context in comments.

2 Comments

this works great. the auto increment id does not get updated either.
Note that this does no longer work with InnoDB. If you want this to work you have to use MyISAM (which comes at a slight performance penalty that gets worse the more concurrent access there are).
2

As of official documentation REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index

You have to specify already use primary key in your statement of for your text field add a unique index to see it in action

For existing primary key eg 1 use

REPLACE INTO `table1` (id,text1) VALUES (1,'Apple1');

DEMO

Another example for unique key

ALTER TABLE `table1` ADD UNIQUE INDEX `indexu` (`text1`); 

Sample data

INSERT INTO `table1` (id,text1) VALUES (1,'Apple');
INSERT INTO `table1` (id,text1) VALUES (2,'Banana');

Lets update id for value Banana

REPLACE INTO `table1` (id,text1) VALUES (5,'Banana');

DEMO

2 Comments

works like charm, but is there any chance that the Auto ID won't get updated? Currently the ID will change once REPLACE INTO is executed. Or I should use 2 queries (1 for checking existence, 1 for inserting?)
@Raptor my second example is for unique index and for explanation i have updated id column but it doesn't mean it will update primary key you can specify other columns in query and when there is any value repeated then it will update that row instead of creating new one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.