duncan
duncan

Reputation: 31912

Order of columns in INSERT INTO ... SELECT * matters?

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

Table1

Table2

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?

Upvotes: 9

Views: 16749

Answers (2)

ADyson
ADyson

Reputation: 61914

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 (e.g. 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

Upvotes: 11

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

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.

Upvotes: 19

Related Questions