Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in SQL by (20.3k 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.4k 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.

You can learn in-depth about SQL statements, queries and become proficient in SQL queries by enrolling in our industry-recognized Microsoft SQL Certification.

Related questions

0 votes
1 answer
asked Jul 20, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
asked Nov 26, 2020 in SQL by Appu (6.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories