Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you duplicate a row without knowing the schema in MySQL? [duplicate]

Tags:

mysql

A great way to duplicate a row in MySQL is to use INSERT INTO ... SELECT FROM syntax.

For example:

INSERT INTO tblExample (col1, col2, col3)
SELECT col1, col2, col3 FROM tblExample WHERE pkey = 1234;

This is easy and straightforward, but from a code maintenance standpoint this is one more statement to keep track of if there are any schema changes. Suppose I add an additional column to the tblExample table, col4; now I have to remember to go back and update this SQL statement in my code. If I fail to do so, then I've just introduced a bug.

With this in mind, is there an easy to way to copy the whole row, whatever the schema may be, except for the primary key?

like image 257
DOOManiac Avatar asked Jul 13 '15 15:07

DOOManiac


1 Answers

Very much against best practices you can do the following:

INSERT INTO myTable
SELECT * FROM myTable WHERE thisField = "abcd"
like image 105
Tingo Avatar answered Oct 11 '22 13:10

Tingo