How to Duplicate a Row in MySQL
Sometimes we need to insert data in our database that is mostly similar to the data of another row. In MySQL, an easy trick is available through which you can easily create a duplicate row.
In this article, we’ll learn how we can create a duplicate of a row in the same table in MySQL, and also we are going to take a look at a relevant example and explain it part by part to make the topic easier.
Create a Duplicate Row in MySQL
The basic idea is to divide the query into two parts where the first part will retrieve specific data that needs to be duplicated, and the second part will copy and insert that data into a new row of the same table.
In our example below, we will illustrate how we can create a duplicate row in MySQL. For the example, suppose we have the following table structure.
Table: projects
Project_ID | Project_name | Members |
---|
For this purpose of duplicating a row and inserting it into the same table, you can follow the below query.
Query:
INSERT INTO projects (Project_ID,Project_name, Members) SELECT 1, Project_name, Members FROM projects WHERE Project_ID = 1
Now let’s explain the query we shared above. The part INSERT INTO projects
will insert the data into the projects
table where the available fields are (Project_ID,Project_name, Members)
.
In the next part, we will retrieve the data from the same fields and table through the line SELECT 1, Project_name, Members FROM projects
. To specify which data needs to be retrieved, we specified a condition in our query: WHERE Project_ID = 1
.
You will get the following output when you execute the above query example.
Please note that the query we used in this article is written in MySQL.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn