0 votes
1 view
in SQL by (22.4k points)

I have a table Eg- tab. What I am trying to do is copying a row with an autoincrement column ID=1 and insert the data into the same table with a row and column ID=2.

Using MySql. How can I do this in a single query? Please help

1 Answer

0 votes
by (40.3k points)

Try using INSERT ... SELECT in this way:

INSERT into your_table (c1, c2, ...)

SELECT c1, c2, ...

FROM your_table

WHERE id = 1

WHERE c1, c2, ... are all the columns except id. 

If you want to explicitly insert with an id of 2 then include that in your INSERT column list and your SELECT clause like this:

INSERT into your_table (id, c1, c2, ...)

SELECT 2, c1, c2, ...

FROM your_table

WHERE id = 1

Note: You need to take care of a possible duplicate id of 2 while writing the second query.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !