2

I am facing a problem regarding inserting data from one table to another table, with the same table structure, but with different column positions.

Example:

Table 1:

     emp1:
          Name    char 50
          Age     int
          Salary  Float

Table 2:

     emp2:
          Name    char 50
          Salary  Float 
          Age     int

My code:

insert into emp1
select * from emp2

I can't insert because the column order is different from one table to the other, but, both tables have same name and data types.

1
  • 1
    You have to specify columns Commented Jun 9, 2017 at 17:40

3 Answers 3

5

You can (or as @marc_s mentioned should) specify columns.

Doing that you can change a structure of these tables (could happen, right?) without any consequences (except if you delete these columns). Your code still working.

Moreover specifying columns name it's just more readable for anybody. You don't need to call sp_help or any other commands to check the structure (table schema).

BTW having a primary key in both tables or any table will throw an exception if not specifying the sought columns only:

If an INSERT statement violates a constraint or rule, or if it has a value incompatible with the data type of the column, the statement fails and an error message is returned.

If INSERT is loading multiple rows with SELECT or EXECUTE, any violation of a rule or constraint that occurs from the values being loaded causes the statement to be stopped, and no rows are loaded.

    INSERT INTO emp1 (Name
        ,Age 
        ,Salary )
    SELECT Name
        ,Age 
        ,Salary
    FROM emp2
Sign up to request clarification or add additional context in comments.

2 Comments

You can, and a best practice says you always should!
@marc_s. =) It's why in comment I mentioned about 'have to'
0

test this query , it should work:

insert into emp1 select Name, Age, Salary from emp2;

and I suggest you to read this tutorial.

Comments

0

It's simple just reorder columns during insert:

INSERT INTO `emp1` (Name, Salary, Age)
SELECT Name, Salary, Age FROM `emp2`;

1 Comment

if its more than 100 fields , its tedious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.