Categories: Programming

Duplicating entire rows in MySQL table to the same table

One line MySQL query to clone entire data from a table to the same table without conflicting primary key.

On a recent large scale web application we were developing at WebCastle, I came across a need to clone complete rows from a MySQL table to same table. Initially we were having 2.5 million product rows in the table. Our requirement was to test our application performance with Sphinx Search engine to load it with 1 million products. Client didn’t had that much products ready yet and we wanted to make it rocket fast and bulletproof.

There were suggestions around the web to copy the rows in to new table and then copy back to original table to avoid duplicate key issue for indexed ID ( primary key ). But I just have a simple idea.  Just below query will do the job of cloning entire rows in to the same table without conflicting primary key

INSERT INTO `TABLENAME` (`field2`, `field3`,… ) SELECT `field2`, `field3`,… FROM TABLENAME

Replace TABLENAME with your table’s name. Care that I kept field2 as the first column name which means, you should not insert in to ID column or select data from it. Just copy the rest and ID will auto increment.

There is one more thing

To get the complete field names within a table, you can just export the table with only one row in it. Again remember to delete primary key field name.

Remiz

Remixed version of unstable human emotions and thirst of mankind actions. UX designer, UI developer and HE of WebCastle Media Pvt LTD

Recent Posts

Revolutionizing Web Development with AI: Tools and Techniques for Improved Productivity and Accuracy

AI is being used in programming to improve efficiency, accuracy and automation. It is being used in machine learning algorithms…

1 year ago

Apple push notification php example code 2021

For a long time since Push notification became a thing on iOS, it was very simple to integrate push notification…

3 years ago

Solved: MySQL convert_tz returns null on MacOS Catalina using XAMPP

Note: A little bit of a story since I haven't been writing for a while. If you are in a…

4 years ago

Why You Should Hire a Creative Marketing Agency for Your Next Campaign

There are few things that are quite as universally important in a business like marketing. Good marketing is at the…

5 years ago

Bring back PPTP VPN on iOS 10 and macOs sierra

Since latest iOS and macOs removed support for PPTP VPN from their built in client, here is how you can…

8 years ago

This will Change

Back to habits of young days. Shaping up another life. Starting like a kid who is a great king.

10 years ago