142

How to change column order in a table using SQL query in SQL Server 2005?

I want to rearrange column order in a table using SQL query.

Maniero
  • 10,311
  • 6
  • 40
  • 85
Himadri
  • 8,600
  • 15
  • 47
  • 70
  • 3
    If you're referring to changing the _position_ of the columns as they exist in the table, you'll need to create a new table with the preferred order, insert the data from the old table, then drop the original table. There's no other way (to my knowledge) to do that. – Michael Todd Oct 22 '09 at 05:24
  • Are you talking about the column order on a SELECT statement, or the column order on the table definition? – marc_s Oct 22 '09 at 05:24

24 Answers24

150

You cannot. The column order is just a "cosmetic" thing we humans care about - to SQL Server, it's almost always absolutely irrelevant.

What SQL Server Management Studio does in the background when you change column order there is recreating the table from scratch with a new CREATE TABLE command, copying over the data from the old table, and then dropping it.

There is no SQL command to define the column ordering.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • MySQL lets you "re-order" the default order using 'alter table'. I would assume MS SQL Server can do that too. (Besides, I think he's just after a query, not storage) – lexu Oct 22 '09 at 05:26
  • 4
    No, there's no such thing ni SQL Server - and should not be in any real RBDMS - column order is not a concept that's relevant to a SQL table – marc_s Oct 22 '09 at 05:27
  • 87
    @marc_s There isn't a good reason against supporting column order. Even if it's only visual. It simply can make it easier to look at the data in a table with a given column order when you make a "SELECT *". I'm a developer and do this kind of queries all the time. You can spare some time with a good pre-defined column order. From any other standpoint, of course, it has no sense: nothing should depend on the column order. By the way, there is an ORDINAL_POSITION column qhen you query "INFORMATION_SCHEMA.COLUMNS". I don't know what it means... but it must have something to do with this. – JotaBe Jun 21 '13 at 12:46
  • 1
    @marc_s you can tell that's not right by a simple test: if you run the same select * statement twice in SQL Server, does it return the columns in the same order? :) – Rob Grant Apr 08 '14 at 14:48
  • 32
    Column order is relevant for example when using INSERT INTO without specifying column names. Another example is ORDER BY column index instead of column name. Both obviously not recommended practices, but SQL Server allows it so someone may have used it somewhere, possibly breaking T-SQL code when changing column order. – Carvellis Jul 07 '14 at 13:38
  • 18
    @Carvelis: you should **NEVER** use `INSERT` without explicitly specifying your columns anyway! – marc_s Jul 07 '14 at 13:38
  • 6
    @marc_s: absolutely, but I'm not usually the only one working on a project. I've seen quite a few projects where people have used this sort of code. – Carvellis Jul 07 '14 at 13:41
  • I have a third party configurable application that uses a SQL Server database that is merge replicated. Any fields added after the rowguid column added by replication don't behave correctly because the app expects the rowguid to be last. Bad programming? of course, but I have to live with it until it is fixed months from now. – Chris Morgan Jul 30 '15 at 20:50
  • 4
    Colum order is relevant (not only cosmetic) when using Entity Framework Code First from existing database generator. Whent there is bad ordering of columns used for composite primary key (although the key is defined properly a well as foreign keys), then you cannot instantiate database context - validation fails. So there is sometimes very good reason and strong need for repair column odrer. – Pavel Hodek Dec 06 '16 at 12:44
  • 1
    FWIW apparently it looks like column order is relevant when using the new temporal features (SYSTEM_VERSIONING), in that the history table has to have the same columns in the same order – lc. Jul 05 '17 at 06:43
  • 2
    Column order is relevant when using BULK INSERT. – paulmorriss Mar 20 '18 at 14:59
  • 3
    The order of columns can matter for large tables as well. From the MS SQL server 2012 internals book: For variable-length columns, NULLs don’t take any space in the variable-length data part of the row. However, as you saw in Listing 6-7, a 2-byte column offset entry still exists for each variable-length column, so you can’t say that they take no space at all. However, if a zero-length value is stored at the end of the list of variable-length data columns, SQL Server doesn’t store any information about it and doesn’t include the 2 bytes in the column offset array. – Robert Pouleijn Jun 08 '18 at 12:53
  • 1
    @Robert Pouleijn - the one person thinking about storage and performance. The order in which data are stored makes a difference to performance and therefore re-ordering columns at the time when new columns are added to a table can improve performance. Answers here that talk about ordering columns in a `SELECT` query miss the mark, I think. So the correct answer is to create a new table, insert into it and drop the original - but then you will have to repeat that in order to reclaim the original table name. It would seem SSMS does this all and is the quickest solution but documents no query. – youcantryreachingme Oct 18 '18 at 02:04
  • Incidentally, using SSMS returned "Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option to Prevent saving changes that require the table to be re-created." So clearly SQLServer does apply a column order, clearly it drops and recreates the table when you drag and drop columns in SSMS and clearly you can enable a setting to prevent dropping tables in this way. – youcantryreachingme Oct 18 '18 at 02:09
  • 4
    The column order of columns is definitely **NOT** just a "cosmetic" @marc_s, or "only visual" @JotaBe. The order can directly impact performance. I have a lecture about `SQL Server internals: Tables structure` where in one of the demo I create two databases > execute the same script which start with creating a table > Result is that one DB is twice the size of the other DB, and I executed the exact same script except of changing the order of one column in the table `:-)`. I gave a full example in the MSDN forums several times as well. – Ronen Ariely Feb 03 '19 at 07:36
  • @RonenAriely. Thank you for your comment. SQL Server is supposed to take care of optimizing the data storage, and getting a huge difference in size simply by changing the column order is terrible. Does it keep true after doing a table maintenance? I suppose it has to do with varX columns, or with indices fill factor. I'd be very grateful if you gave a pointer to any of those MSDN examples. I have not been able to find them. – JotaBe Feb 04 '19 at 12:24
  • Hi @JotaBe I was told in past that we are not allowed to add external links here and I try honor the rules in every place that I am guest.I can tell you that I am Moderator at MSDN and this rule does not exists there and we have no problem with links there which point here.IT might be one of many reasons I do not come here a lot, since I do not like to write long answer when I could simply point to a blog. This is not related to variable data length type necessarily and in fact in the specific example I meant in the forum I used char(10). This has nothing to do with "fill factor" as well :-) – Ronen Ariely Feb 05 '19 at 07:15
  • 3
    Even after 10 years, that answer still blows my mind. The fact that there are standard and best practice doesn't change the fact that column ordering is a practical things that most dev DO use all the time. we shouldn't use Select * or any shortcut for that matter and explicitly declare but when we're working on table design or just plain testing, fectching data for development or whatever else, having the data in an order that makes sense helps a lot to save time and confusion. Plus, every single GUI software show you the column in that order, which help you eyes find the information quicker. – Johnny Prescott Feb 10 '21 at 20:44
36

You have to explicitly list the fields in the order you want them to be returned instead of using * for the 'default' order.

original query:

select * from foobar

returns

foo bar
--- ---
  1   2

now write

select bar, foo from foobar

bar foo
--- ---
  2   1
lexu
  • 8,766
  • 5
  • 45
  • 63
  • The answer above is wrong is it not? This answer literally shows how to order the columns, why does the previous one have a checkmark and this one does not? – Agent Lu Jul 11 '19 at 15:00
  • 1
    @Agent Lu The problem is the wording of the original question. Marc and I have interpreted the OP's question for 'change the order of the columns' differently. He makes a strong argument why column order is irrelevant in the stored table (names are though). I showed how data can be extracted in a different column order. Not the same thing at all! – lexu Sep 02 '19 at 16:25
28

according to https://learn.microsoft.com/en-us/sql/relational-databases/tables/change-column-order-in-a-table

This task is not supported using Transact-SQL statements.

Well, it can be done, using create/ copy / drop/ rename, as answered by komma8.komma1

Or you can use SQL Server Management Studio

  1. In Object Explorer, right-click the table with columns you want to reorder and click Design (Modify in ver. 2005 SP1 or earlier)
  2. Select the box to the left of the column name that you want to reorder. (You can select multiple columns by holding the [shift] or the [ctrl] keys on your keyboard.)
  3. Drag the column(s) to another location within the table.

Then click save. This method actually drops and recreates the table, so some errors might occur.

If Change Tracking option is enabled for the database and the table, you shouldn't use this method.

If it is disabled, the Prevent saving changes that require the table re-creation option should be cleared in Tools menu > Options > Designers, otherwise "Saving changes is not permitted" error will occur.

  • Disabling the Prevent saving changes that require the table re-creation option is strongly advised against by Microsoft, as it leads to the existing change tracking information being deleted when the table is re-created, so you should never disable this option if Change Tracking is enabled!

Problems may also arise during primary and foreign key creation.

If any of the above errors occur, saving fails which leaves you with the original column order.

robotik
  • 1,837
  • 1
  • 20
  • 26
  • 1
    The statement "`This task cannot be performed using Transact-SQL statements.`" in the document was wrong. I explained the author and asked him to change it into "`This task is not supported using Transact-SQL statements.`". About a day ago, the author agreed and the document was fixed. [You can follow the discussion we had on GitHub](https://github.com/MicrosoftDocs/sql-docs/issues/3273). – Ronen Ariely Oct 17 '19 at 07:32
  • @RonenAriely good job, and thanks for letting me know. I updated my answer – robotik Oct 22 '19 at 09:56
  • You are most welcome @robotik . I hope that all these who come here and see the response with the most votes will understand that it is a total mistake. Unfortunately, Communities usually behave like a herd (cattle) and once a leader and a top contributor (who is considered top expert) in the community made a mistake, then others follow him, as happened in this thread. People continue to vote for a mistake if it already got many votes (the approach of: "since everyone say so, then it is true"), and other people that will come to the forum will think that this is the correct answer. – Ronen Ariely Oct 22 '19 at 11:50
  • 1
    @RonenAriely that's why i always scroll down :) – robotik Oct 22 '19 at 21:33
18

In SQLServer Management Studio:

Tools -> Options -> Designers -> Table and Database Designers

  • Unselect 'Prevent saving changes that require table re-creation'.

Then:

  • right click the table you want to re-order the columns for.
  • click 'Design'.
  • Drag the columns to the order you want.
  • finally, click save.

SQLServer Management studio will drop the table and recreate it using the data.

Tim Connolly
  • 180
  • 2
  • 8
15

This is similar to the question on ordering the records in the result of a query .. and typically no one likes the formally correct answer ;-)

So here it goes:

  • as per SQL standard, the columns in a table are not "ordered"
  • as a result, a select * does not force the columns to be returned in a particular order
  • typically, each RDBMS has a kind of "default" order (usually the order that the columns were added to the table, either in the create table' or in thealter table add ` statements
  • therefore, if you rely on the order of columns (because you are using the results of a query to poulate some other datastructure from the position of the columns), explicitly list the columns in the order you want them.
Thorsten
  • 12,921
  • 17
  • 60
  • 79
11

You can of course change the order of the columns in a sql statement. However if you want to abstract tables' physical column order, you can create a view. i.e

CREATE TABLE myTable(
    a int NULL,
    b varchar(50) NULL,
    c datetime NULL
);


CREATE VIEW vw_myTable
AS
SELECT c, a, b
  FROM myTable;

select * from myTable;
a  b  c
-  -  -

select * from vw_myTable
c  a  b
-  -  -
mevdiven
  • 1,902
  • 2
  • 17
  • 33
9

You can do it by creating a new table, copy all the data over, drop the old table, then renaming the new one to replace the old one.

You could also add new columns to the table, copy the column by column data over, drop the old columns, then rename new columns to match the old ones. A simple example below: http://sqlfiddle.com/#!3/67af4/1

CREATE TABLE TestTable (
    Column1 INT,
    Column2 VARCHAR(255)
);
GO

insert into TestTable values(1, 'Test1');
insert into TestTable values(2, 'Test2');
GO

select * from TestTable;
GO

ALTER TABLE TestTable ADD Column2_NEW VARCHAR(255);
ALTER TABLE TestTable ADD Column1_NEW INT;
GO

update TestTable 
set Column1_NEW = Column1, 
    Column2_NEW = Column2;
GO

ALTER TABLE TestTable DROP COLUMN Column1;
ALTER TABLE TestTable DROP COLUMN Column2;
GO

sp_rename 'TestTable.Column1_NEW', 'Column1', 'COLUMN';
GO
sp_rename 'TestTable.Column2_NEW', 'Column2', 'COLUMN';
GO

select * from TestTable;
GO
komma8.komma1
  • 1,250
  • 2
  • 14
  • 20
  • 1
    i wrote a stored procedure which does something similar. It automates the table rebuilding using dynamic SQL. https://caseyplummer.wordpress.com/2013/07/22/sql-procedure-to-rebuild-a-table-using-a-specific-column-order/ – Casey Plummer Sep 22 '15 at 19:40
6

In SQLServer Management Studio:

Tools -> Options -> Designers -> Table and Database Designers

Unselect Prevent saving changes that require table re-creation.

Now you can reorder the table.

ata
  • 3,398
  • 5
  • 20
  • 31
3

Sql server internally build the script. It create a temporary table with new changes and copy the data and drop current table then recreate the table insert from temp table. I find it from "Generate Change script" option ssms 2014. Script like this. From Here: How to change column order in a table using sql query

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_emps
    (
    id int NULL,
    ename varchar(20) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_emps SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.emps)
     EXEC('INSERT INTO dbo.Tmp_emps (id, ename)
        SELECT id, ename FROM dbo.emps WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.emps
GO
EXECUTE sp_rename N'dbo.Tmp_emps', N'emps', 'OBJECT' 
GO
COMMIT
Subhankar
  • 31
  • 3
2

If your table has enough columns then you can try this. First create a new table with preferred order of columns.

    create table new as select column1,column2,column3,....columnN from table_name;

Now drop the table using drop command

    drop table table_name;

now rename the newly created table to your old table name.

    rename new to table_name;

now select the table, you have your columns rearranged as you preferred before.

    select * from table_name;
  • This is the same as create a new table, copy data from the existing table to the new one, delete the old one and rename the new one. So strictly speaking , this is not changing the column order of the table. As this creates / copies from the old table, it takes time for huge tables. Last but not least, the proposed syntax does not work in t-sql. – Jean-François Dec 14 '19 at 00:35
2

Not sure if still relevant, but SSMS can generate a change scripts for this.

  1. Re-order (drag the column) the table in Designer View
  2. Click on 'Generate Change Script'

enter image description here

The generated script contains the script which does the following:

  1. Create a temporary table
  2. Adds the constraints, relationships and triggers from original table to temporary table
  3. Drop original table
  4. Rename temporary table to original table name
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

If you have not yet added any data into your table yet, there is one way to move the columns around. Try this:

  1. In SSMS, click Tools > Options > Designers > Table and Database Designers > Uncheck the box next to Prevent saving changes that require table re-creation > Click OK.
  2. In the object tree, right-click on your table and select Design > in the thin column to the left of the Column Name column, you can click and drag the columns around to wherever you want them. When you're done, just go to close the Design tab and SSMS will ask you if you want to save your changes, click OK.

Optional: 3. Re-enable the checkbox for the option from Step 1 to re-secure your table.

Hope this helps someone!

Credit goes to Microsoft: https://learn.microsoft.com/en-us/troubleshoot/sql/ssms/error-when-you-save-table#more-information

Zee
  • 11
  • 2
0

At the end of the day, you simply cannot do this in MS SQL. I recently created tables on the go (application startup) using a stored Procedure that reads from a lookup table. When I created a view that combined these with another table I had manually created earlier one (same schema, with data), It failed - simply because I was using ''Select * UNION Select * ' for the view. At the same time, if I use only those created through the stored procedure, I am successful.

In conclusion: If there is any application which depends on the order of column it is really not good programming and will for sure create problems in the future. Columns should 'feel' free to be anywhere and be used for any data process (INSERT, UPDATE, SELECT).

Chagbert
  • 722
  • 7
  • 16
0

You can achieve it with these steps:

  1. remove all foreign keys and primary key of the original table.

  2. rename the original table.

  3. using CTAS create the original table in the order you want.

  4. drop the old table.

  5. apply all constraints back to the original table

Pang
  • 9,564
  • 146
  • 81
  • 122
0

If the columns to be reordered have recently been created and are empty, then the columns can be deleted and re-added in the correct order.

This happened to me, extending a database manually to add new functionality, and I had missed a column out, and when I added it, the sequence was incorrect.

After finding no adequate solution here I simply corrected the table using the following kind of commands.

ALTER TABLE  tablename  DROP COLUMN  columnname; 
ALTER TABLE  tablename  ADD columnname columntype;

Note: only do this if you don't have data in the columns you are dropping.

People have said that column order does not matter. I regularly use SQL Server Management Studio "generate scripts" to create a text version of a database's schema. To effectively version control these scripts (git) and to compare them (WinMerge), it is imperative that the output from compatible databases is the same, and the differences highlighted are genuine database differences.

Column order does matter; but just to some people, not to everyone!

Ivan
  • 4,383
  • 36
  • 27
0

No, this is not possible, you will need to recreate the table. However, this is possible for version of SQL Server 2016 (13.x and above ) from table design only ( you cannot do that with a specific SQL query )

See this: https://learn.microsoft.com/en-us/sql/relational-databases/tables/change-column-order-in-a-table?view=sql-server-ver16

Soufiane N
  • 113
  • 1
  • 11
-2

Use

SELECT * FROM TABLE1

which displays the default column order of the table.

If you want to change the order of the columns.

Specify the column name to display correspondingly

SELECT COLUMN1, COLUMN5, COLUMN4, COLUMN3, COULMN2 FROM TABLE1
solairaja
  • 966
  • 7
  • 17
-2

you can use indexing.. After indexing, if select * from XXXX results should be as per the index, But only result set.. not structrue of Table

Karthik.M
  • 67
  • 11
-2

In order to have a specific column order You need to select column by column in the order You wish. Selection order dictates how columns will be ordered in output.

-2

Try this command:

alter table students modify age int(5) first; 

This will change the position of age to the first position.

veben
  • 19,637
  • 14
  • 60
  • 80
-3

You can change this using SQL query. Here is sql query to change the sequence of column.

ALTER TABLE table name 
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;
  • I wonder if this drops and recreates the table like in SSMS. Either way I wouldn't roll the dice doing this on a production DB, though this method seems interesting and worth some looking into. – samus Dec 03 '15 at 21:22
  • This functionality does not work in SQL Server as was specified by the OP. Wish it did. – Bill Mar 11 '16 at 17:48
  • 2
    This is MySQL syntax, not SQL Server. – Jon Schneider Feb 08 '17 at 15:24
-3

alter table name modify columnname int(5) first; will bring the column to first alter table name modify columnname int(5) after (tablename);

-3

This worked for me on Oracle DB:

select column1, column2, t.* from table t
blueNinja
  • 1
  • 1
  • 1
-4

Example: Change position of field_priority after field_price in table status.

ALTER TABLE `status` CHANGE `priority` `priority` INT(11) NULL DEFAULT NULL AFTER `price`;
lecaoquochung
  • 123
  • 1
  • 5