简体   繁体   中英

Order of columns in INSERT INTO … SELECT * matters?

Say I've got 2 tables in a MySQL DB:

Table1

  • ID
  • Name
  • Type

Table2

  • ID
  • Type
  • Name

And I want to import a row from Table1 to Table2 using this syntax rather than naming all the columns:

INSERT INTO Table2 SELECT * FROM Table1 WHERE ID = 101

Does the fact the columns are in a different order matter? Or as long as all the columns have the same names, will it work?

There is an actual column order to each of the two tables, which you may see by inspecting the information schema table. However , you should not rely on this, because it may change at some point in the future.

So, best practice is to always specify the columns involved with an INSERT , including in the case of an INSERT INTO ... SELECT :

INSERT INTO Table2 (ID, Name, Type)
SELECT ID, Name, Type
FROM Table1
WHERE ID = 101;

The above query will always behave as you would expect, regardless of the underlying column order in each table.

The order matters. The names are irrelevant.

Better to name your columns explicitly in the order you want them, rather then using select *, and rather than omitting them entirely from the insert side.

This means that it's completely clear to anyone reading it what the code is doing, there's no danger of the SQL engine misinterpreting the instruction, and also any changes to the definition of either table (eg fields added, or the order changed) will not break the query.

For example (using a scenario where neither name nor order matches):

INSERT INTO Table2 (field1, field5, field2)
SELECT fieldA, fieldC, fieldX 
FROM Table1 
WHERE ID = 101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM