JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

Validating inserted values in MySQL table with duplicate key

Author:JIYIK Last Updated:2025/04/09 Views:

Traditional SQL INSERTstatements do not perform input validation of their parameters/values ​​against existing database tables, which sometimes results in errors when duplicate keys are found during the insert process.

This is handled in MySQL through INSERTthe extension of the AND ON DUPLICATE KEY UPDATE, REPLACEand statements.IGNORE

To illustrate these methods, let's create a sample database called programming_languages.

-- Here goes the definition of the database
CREATE DATABASE programming_languages;
USE programming_languages;

-- Creating a table
CREATE TABLE Details(
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(25) UNIQUE,    -- Making name column unique 
    year_released VARCHAR (5),
    PRIMARY KEY(id)
    );

Output:

20:22:03	CREATE DATABASE programming_languages	1 row(s) affected	0.219 sec
20:22:03	USE programming_languages	0 row(s) affected	0.000 sec
20:22:03	CREATE TABLE Details(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(25) UNIQUE,     year_released VARCHAR (5),PRIMARY KEY(id)) 0 row(s) affected	0.625 sec

Now the details table will be populated with values ​​like below.

-- Names of popular programming languages and their release year
INSERT INTO Details (name, year_released) VALUES ('python', 1991),('c++', 1985),('Java', 1995);

SELECT * FROM Details ORDER BY id;    -- Previewing table

Output:

id	name	year_released
1	python	1991
2	c++		1985
3	Java	1995

-----------------------------------------------------------------------------------------
20:23:24	INSERT INTO Details (name, year_released) VALUES ('python', 1991),('c++', 	     1985),('Java',1995) 3 row(s) affected Records: 3 Duplicates: 0 Warnings: 0	0.109 sec

20:23:24	SELECT * FROM Details ORDER BY id LIMIT 0, 1000	3 row(s) returned 0.000 sec /     0.000 sec

We try to insert a row called into the table python. As expected, this operation results in an error.

-- Trying to insert a new value
INSERT INTO Details (name, year_released) VALUES ('python', 1992)

Output:

20:27:31	INSERT INTO Details (name, year_released) VALUES ('python',1992) Error Code:     1062. Duplicate entry 'python' for key 'details.name' 0.046 sec

ON DUPLICATE KEYInserting values ​​in MySQL table with duplicate key validation using update method

This method either inserts new values ​​(if they don't exist in the table) or updates an existing row. So if a row contains the same data as the new insert, MySQL doesn't make any changes. However, if its data is different from the insert query, it updates the row. If the row doesn't exist, it inserts it.

INSERT INTO Details (name, year_released) VALUES ('python', 1992) as V ON DUPLICATE KEY UPDATE name = V.name, year_released = V.year_released;

SELECT * FROM Details ORDER BY id;   -- Checking the output

Output:

id	name	year_released
1	python	1992
2	c++		1985
3	Java	1995

-----------------------------------------------------------------------------------------
20:47:35	INSERT INTO Details (name, year_released) VALUES ('python', 1992) as V ON         DUPLICATE KEY UPDATE name = V.name, year_released = V.year_released 2 row(s) affected     0.172 sec

20:49:23	SELECT * FROM Details ORDER BY id LIMIT 0, 1000	3 row(s) returned	0.000 sec     / 0.000 sec

From the output, observe that year_releasedthe column has pythonbeen updated for and the logs indicate that two (2) rows were affected (a typical row update operation). You can refer to the official reference of this extension for more options.


REPLACEInsert values ​​in MySQL table with duplicate key validation using

Use this method with caution! Unlike the previous extension, it deletes the row and inserts a new row containing the desired data. While this may appear benign, it can be problematic if a row's unique relationship is deleted during the operation.

REPLACE INTO Details (name, year_released) VALUES ('python', 1993);
SELECT * FROM Details ORDER BY id;

Output:

id	name	year_released
2	c++		1985
3	Java	1995
7	python	1993
-----------------------------------------------------------------------------------------
20:56:48	REPLACE INTO Details (name, year_released) VALUES ('python', 1993) 2 row(s)       affected 0.093 sec

Now, observe Insertthat the operation is performed. However, idit has been changed (due to deletions and insertions). It is recommended to review the official reference of this extension to determine safe usage and extra options.


IGNOREInsert values ​​in MySQL table with duplicate key validation using

IGNOREMethod duplicate keyshas no effect on rows with . However, it does not INSERTthrow an error for the operation. This method handles situations where the update is not allowed and does not require an exception/error to be thrown.

INSERT IGNORE INTO Details (name, year_released) VALUES ('python', 1991);
SELECT * FROM Details ORDER BY id;

Output:

id	name	year_released
2	c++		1985
3	Java	1995
7	python	1993
-----------------------------------------------------------------------------------------
21:29:44	INSERT IGNORE INTO Details (name, year_released) VALUES ('python', 1991) 0 	     row(s) affected, 1 warning(s): 1062 Duplicate entry 'python' for key 'details.name'	0.157 sec

As expected, MySQL does not throw any errors. However, the table remains unchanged.

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.

Article URL:

Related Articles

If ELSE in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

In this tutorial, we aim to explore how to use IF ELSE the statement in MySQL. One of the key roles of a data analyst is to gather insights from the data and produce meaningful results. It can be done with the help of several data filtering

DATETIME vs. TIMESTAMP in MySQL

Publish Date:2025/04/11 Views:117 Category:MySQL

DATETIME and TIMESTAMP are two different data types that can be used to store values ​​that must contain both a date and a time portion. In this article, we will understand how it is stored in the database and the memory required for ea

Execute multiple joins in one query in MYSQL

Publish Date:2025/04/11 Views:94 Category:MySQL

Have you ever wondered how to include multiple joins in one query in MySQL? You have come to the right place. Remember that joins allow us to access information from other tables. This information is included separately to avoid redundancy.

Joining 3 tables in MySQL

Publish Date:2025/04/11 Views:187 Category:MySQL

In this tutorial, we will learn how to join three tables in MySQL. Businesses and organizations may have to visualize three tables simultaneously based on certain matching columns common to all three tables. This operation is allowed in MyS

Use of UPDATE JOIN in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

This tutorial will explain how to use the statement in MySQL database UPDATE JOIN . We generally use joins to iterate over the rows in a particular table which may or may not have similar rows in other tables. We can UPDATE use JOIN the cla

How to use the Row_Number() function in MySQL

Publish Date:2025/04/11 Views:142 Category:MySQL

In this tutorial, we will explain how to use the VALUES function in MySQL ROW_NUMBER() . This is a sorting method that assigns consecutive numbers within a partition starting from 1. It is important to note that no two rows within a partiti

Multiple primary keys in MySQL

Publish Date:2025/04/11 Views:66 Category:MySQL

In this tutorial, our goal is to explore the concept of multiple primary keys for a table in MySQL. Many times, businesses and organizations have to assign certain columns as primary keys. This primary key has multiple uses and reasons to b

Displaying foreign keys in MySQL

Publish Date:2025/04/11 Views:55 Category:MySQL

In this tutorial, we aim to explore how to display foreign keys for tables and columns in MySQL. The type of key that references a primary key, also known as the primary key of another table, is called a foreign key. Understanding the forei

Select first N rows in MySQL

Publish Date:2025/04/11 Views:85 Category:MySQL

Sometimes, you have to select first N rows of MySQL database according to your project requirements. n The value of varies according to the requirement; it can be TOP 1 row or TOP 30 rows. We will learn how to select top N rows using the cl

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial