87

How do I add a column after another column within MS SQL by using SQL query?

TempTable ID int, Type nvarchar(20), Active bit

NewTable ID int, Type nvarchar(20), Description text, Active bit

That is what I want, how do I do that

3
  • 1
    Column order is irrelevant to SQL. You can define column order in SELECT, INSERT or UPDATE statements. Commented Nov 3, 2010 at 3:43
  • 1
    Yeah I know, but I just like things structured a certain way Commented Nov 3, 2010 at 6:13
  • 1
    since column order really isn't relevant, there's no such feature in SQL Server / T-SQL. You need to either use the interactive table designer (which will re-create the entire table in the process), or you just have to let it be. Commented Nov 3, 2010 at 6:30

3 Answers 3

167

Add a column to the end of the table:

ALTER TABLE myTable ADD myNewColumn VARCHAR(255);

Add a column to the start of the table:

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) FIRST;

Add a column after an existing column:

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn;

For additional options, see MySQL's ALTER TABLE documentation.

Sign up to request clarification or add additional context in comments.

10 Comments

this is MS SQL not MySQL unfortunately
In that case, I believe you have to recreate the entire table. Why does column order matter?
I am just really picky like that, and prefer tables to have a certain order. Ok I will just have to recreate it
Heh, fair enough. Maybe add the column, then add copies of the columns that you want to be after the added column, update the column values, drop old columns and rename the new. A pain, but necessary.
I tried it on MYSQL and it worked for me. Server: MySQL Version: 5.5.29 Engine InnoDB.
|
9

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

Comments

2

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

Comments

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.