If it exists then update the record, otherwise insert it into the MySQL table
A database administrator may occasionally need to add a record to a MySQL table, or update a frequently occurring record. MySQL will send an alert if a user attempts to insert a record that already exists or has a duplicate PRIMARY KEY value.
This article outlines methods you can use to correct this error and achieve better results.
If it exists then update the record, otherwise insert it into the MySQL table
MySQL provides several useful statements when you need to insert a row after determining whether the row is actually new or already exists.
If the record exists then update the record using REPLACE INTO else insert it into MySQL table
If INSERT
the command fails due to duplicate UNIQUE
or PRIMARY KEY
values, as mentioned earlier, if you want to actually replace the row, one way is to use the REPLACE statement.
When you use the REPLACE INTO statement, each command issued can have two possible results:
- A typical INSERT statement is executed because no row with the required value can be found.
- When a matching row is found, the existing row is deleted using the usual DELETE statement, and then a standard INSERT is performed.
For example, suppose we have an employees table with id, department, employee_name, and joining_year columns. We have decided to change our department and joining_year of id = 101
records back to the original operational records.
-- Before update
SELECT * from employees where id = 101;
REPLACE INTO employees
(id, department, employee_name, joining_year)
VALUES
(101, 'Operations', 'John Doe', 2013);
-- After update
SELECT * from employees where id = 101;
Run the above line of code in any MySQL compatible browser. It will display the following result:
-- Before update
+----+------------+---------------+----------------+
| id | department | employee_name | year_published |
+----+------------+---------------+----------------+
|101 | Technology | John Doe | 2017 |
+----+------------+---------------+----------------+
Query OK, 2 rows affected (0.01 sec)
-- After update
+----+------------+---------------+----------------+
| id | department | employee_name | year_published |
+----+------------+---------------+----------------+
|101 | Operations | John Doe | 2013 |
+----+------------+---------------+----------------+
In this example, even though we only changed one item, the results show that two rows were affected because we deleted the previous record and then inserted the new row to replace it.
Use INSERT ... ON DUPLICATE KEY UPDATE to update the record if it exists otherwise insert it into the MySQL table
We can use INSERT ... ON DUPLICATE KEY UPDATE
the INSERT statement and the VALUES clause as an alternative to inserting into rows that might have duplicate UNIQUE or PRIMARY KEY values.
Using INSERT ... ON DUPLICATE KEY UPDATE is nondestructive by issuing only INSERT or UPDATE instructions and not DELETEs, compared to REPLACE, which is inherently harmful because it executes a DELETE command when necessary.
For example, suppose we have an employees table with id, department, employee_name and joining_year columns. We have decided to change our department and joining_year of id = 101 record back to the original operation record.
Now we can add the new ON DUPLICATE KEY UPDATE clause to our original INSERT statement:
-- Before update
SELECT * from employees where id = 101;
SET @id = 101,
@department = 'Operations',
@employee_name = 'John Doe',
@joining_year = 2013;
INSERT INTO employees
(id, department, employee_name, joining_year)
VALUES
(@id, @department, @employee_name, @joining_year)
ON DUPLICATE KEY UPDATE
department = @department,
employee_name = @employee_name,
joining_year = @joining_year;
-- After update
SELECT * from employees where id = 101;
In the example above, we chose to use user variables to avoid declaring multiple times the actual value we wish to INSERT or UPDATE, even though ON DUPLICATE KEY UPDATE
it is not necessary for the method to work as expected.
Run the above line of code in any browser compatible with MySQL. It will display the following result:
-- Before update
+----+------------+---------------+----------------+
| id | department | employee_name | year_published |
+----+------------+---------------+----------------+
|101 | Technology | John Doe | 2017 |
+----+------------+---------------+----------------+
Query OK, 1 rows affected (0.00 sec)
-- After update
+----+------------+---------------+----------------+
| id | department | employee_name | year_published |
+----+------------+---------------+----------------+
|101 | Operations | John Doe | 2013 |
+----+------------+---------------+----------------+
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Get the version in MySQL
Publish Date:2025/04/24 Views:169 Category:MySQL
-
In this article, we will learn how to get the current version of MySQL on Windows systems. It is necessary for businesses to maintain versions of different tools and software used to run their business in order to keep systems compatible. T
Full Join in MySQL
Publish Date:2025/04/24 Views:70 Category:MySQL
-
This article aims to explore how to perform a full join or full outer join in MySQL. Full outer join is used to merge or combine the entire data from two separate tables. For example, suppose we have two tables named student_id and student_
Grouping by month in MySQL
Publish Date:2025/04/24 Views:166 Category:MySQL
-
In this article, we will learn how to group values by month in MySQL database. Businesses and organizations have to find user or customer data based on purchase or usage trends over a few months. If a particular business achieves its
Enabling the slow query log in MySQL
Publish Date:2025/04/24 Views:177 Category:MySQL
-
Today, we will enable MySQL in MySQL using MySQL shell on Windows and Ubuntu 20.04 slow_query_log . For this tutorial, we are using MySQL version 8.0 and Ubuntu 20.04. MySQL slow_query_log MySQL slow_query_log contains SQL statements that t
Update multiple tables in MySQL with one query
Publish Date:2025/04/24 Views:65 Category:MySQL
-
In some cases, users want to update logically related tables at the same time. These logically related tables are linked to each other through some attributes. Advantages of updating multiple tables in one MySQL query Similar attributes in
Checking MySQL version in macOS
Publish Date:2025/04/24 Views:60 Category:MySQL
-
In this article, we aim to explore how to check the current version of MySQL on macOS. Checking MySQL version in macOS When trying to figure out the version, you must follow these steps. Each time a person logs into the MySQL server, the ve
Common table expressions in MySQL
Publish Date:2025/04/24 Views:168 Category:MySQL
-
This article aims to understand how to use common table expressions in MySQL. Most data analysts need to store the results of different queries in order to merge them with a separate query. With the help of common tables, expressions can ma
Sorting by date in MySQL
Publish Date:2025/04/24 Views:156 Category:MySQL
-
This article aims to understand how to sort values by date in MySQL. Most of the businesses and organizations that use MySQL for data analysis or data visualization need to sort different table values of their users based on dat
Sort MySQL data alphabetically
Publish Date:2025/04/24 Views:153 Category:MySQL
-
In this article, we aim to explore how to sort data alphabetically in MySQL database. Sorting is the ordering of elements or values in an array or column based on a particular criteria. In this tutorial, we will set the criteria as al