Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: SQL insert query to duplicate data in same table

Tags:

sql

mysql

I have a table say table1(id, col2, col3), and I want to duplicate all data of id 1 but with different id say 11 (id is not auto generated column). I wrote the following sql query which is not working for me (giving syntax error):

INSERT INTO table1(
id,
col2,
col3
)
VALUES (

SELECT 11 , col2, col3
FROM table1 WHERE id=1
)
like image 291
gmuhammad Avatar asked Sep 03 '12 11:09

gmuhammad


People also ask

How do you duplicate data in the same table in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

How can I get duplicate data from a table in MySQL?

Find duplicate values in one column First, use the GROUP BY clause to group all rows by the target column, which is the column that you want to check duplicate. Then, use the COUNT() function in the HAVING clause to check if any group have more than 1 element. These groups are duplicate.

How do you insert duplicates in SQL?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.

How do I insert a select query result into a table?

From the Query Designer menu, point to Change Type, and then click Insert Results. In the Choose Target Table for Insert Results Dialog Box, select the table to copy rows to (the destination table).


2 Answers

Don't use the "VALUES" keyword

INSERT INTO table1(
id,
col2,
col3
)


SELECT 11 , col2, col3
FROM table1
WHERE id = 1

EDIT :

Check if you're working with the right column names :

DESC table1;
like image 172
Raphaël Althaus Avatar answered Sep 18 '22 00:09

Raphaël Althaus


Try this:

INSERT INTO table1(
id,
col2,
col3
)
SELECT 11 , col2, col3
FROM table1
WHERE table1.id = 1

OR if you need more something like this:

INSERT INTO table1(id, col2, col3)
SELECT (SELECT MAX(id) FROM table1) + 1 , col2, col3
FROM table1
like image 35
András Ottó Avatar answered Sep 21 '22 00:09

András Ottó