Quickly duplicate a row in MySQL

A quick way of duplicating a row in a table without running into duplicate key errors or having to type out all the field names…

Not quite a one-liner, but very straightforward.

/*
Duplicate row 58 from mytable
*/
CREATE TEMPORARY TABLE tmptable  SELECT * FROM mytable WHERE id = 58;
 
/*
Change the unique key
*/
UPDATE tmptable SET id=0; 
 
/* 
Insert the duplicate row into the original table
*/
INSERT INTO mytable SELECT * FROM tmptable;
 
/* 
Drop the temporary table
*/
DROP TABLE tmptable;

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>