Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO...SELECT for all MySQL columns

I'm trying to move old data from:

this_table >> this_table_archive

copying all columns over. I've tried this, but it doesn't work:

INSERT INTO this_table_archive (*) VALUES (SELECT * FROM this_table WHERE entry_date < '2011-01-01 00:00:00');

Note: the tables are identical and have id set as a primary key.

like image 355
Kyle Cureau Avatar asked Oct 18 '22 11:10

Kyle Cureau


People also ask

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

How can insert selected values in a table in MySQL?

The MySQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables matches. Note: The existing records in the target table are unaffected.

Does MySQL support bulk insert?

The INSERT statement in MySQL also supports the use of VALUES syntax to insert multiple rows as a bulk insert statement. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.


2 Answers

The correct syntax is described in the manual. Try this:

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

If the id columns is an auto-increment column and you already have some data in both tables then in some cases you may want to omit the id from the column list and generate new ids instead to avoid insert an id that already exists in the original table. If your target table is empty then this won't be an issue.

like image 219
Mark Byers Avatar answered Oct 20 '22 13:10

Mark Byers


For the syntax, it looks like this (leave out the column list to implicitly mean "all")

INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'

For avoiding primary key errors if you already have data in the archive table

INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
  AND a.id is null  # does not yet exist in archive
like image 79
RichardTheKiwi Avatar answered Oct 20 '22 11:10

RichardTheKiwi