INSERT INTO...SELECT for all MySQL columns INSERT INTO...SELECT for all MySQL columns mysql mysql

INSERT INTO...SELECT for all MySQL columns


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

INSERT INTO this_table_archive (col1, col2, ..., coln)SELECT col1, col2, ..., colnFROM this_tableWHERE 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.


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

INSERT INTO this_table_archiveSELECT *FROM this_tableWHERE 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_archiveSELECT t.*FROM this_table tLEFT JOIN this_table_archive a on a.id=t.idWHERE t.entry_date < '2011-01-01 00:00:00'  AND a.id is null  # does not yet exist in archive


Addition to Mark Byers answer :

Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.

INSERT INTO matrimony_domain_details (domain, type, logo_path)SELECT 'www.example.com', type, logo_pathFROM matrimony_domain_detailsWHERE id = 367

Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.