Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO ... SELECT without detailing all columns

How do you insert selected rows from table_source to table_target using SQL in MySQL where:

  • Both tables have the same schema
  • All columns should transfer except for the auto-increment id
  • Without explicitly writing all the column names, as that would be tedious

The trivial INSERT INTO table_target SELECT * FROM table_source fails on duplicate entries for primary key.

like image 692
Jonathan Livni Avatar asked Nov 28 '11 14:11

Jonathan Livni


People also ask

How do you exclude columns in select statement?

The information_schema. COLUMNS table holds all information about the columns in your MySQL tables. To exclude columns, you use the REPLACE() and GROUP_CONCAT() functions to generate the column names you wish to include in your SELECT statement later.

Is it possible to only insert data in specific columns?

It is also possible to only insert data in specific columns.

Can insert be used with select?

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.


1 Answers

Either you list all of the fields you want in the insert...select, or you use something else externally to build the list for you.

SQL does not have something like SELECT * except somefield FROM, so you'll have to bite the bullet and write out the field names.

like image 97
Marc B Avatar answered Sep 24 '22 13:09

Marc B