REPLACE INTO instead of INSERT INTO – MySQL

0 min read 130 words

There are many occasions where you need to INSERT a record into a MySQL database table, but the record already exists.

INSERT INTO queue_domains (domain) VALUES('statvoo.com')

This will result in a Duplicate entry 'statvoo.com' for key 'domain' error

A nice and simple way to resolve this is to use REPLACE INTO instead.

This will look to see if the item already exists and will simply replace it.

This is faster than doing a SELECT followed by an INSERT.

If you have an auto_increment column set up, then it will delete the previous record and recreate it with a new auto_increment_id.

How to write the new syntax

Just replace the INSERT INTO with REPLACE INTO and you’re done.

So the above failing SQL statement will become:

REPLACE INTO queue_domains (domain) VALUES('statvoo.com')

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts