Link to home
Start Free TrialLog in
Avatar of Rias
RiasFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How to rearrange column in a sql table by query


How do I write a query to rearrange a column in table.
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

In SQL Server this is not possible, either manually or within a query.  

Microsoft Access has this functionality where in the table designer you can click-and-drag columns to change the order, but SQL Server does not.

What you can do is either backup/drop/re-create/re-populate the table with the new column order, or create a view that selects from your table in the column order you wish.
Do you want to sort the output of the query based on some column(s)?

In such case you can use "order by"
what do you mean? You to really change the order in the definition of the table? For that you need to create a new table with columns in the correct order, copy all the data from the existing table to the new one, drop the existing table and finally rename the new one. After that, you will also need to recreate all indexes.

Or another way is to use the SSMS table designer (which will do all the script for you).
Avatar of Rias


If not then is there any way i can insert a column in a table before another column ?
You can do it using the design view in SSMS (Sql Server Management Studio).
open the table designer in SSMS, select one of the column and click the INSERT key. That will insert a new column in between
Avatar of Rias


need to have it in query ,please.
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rias


Éric Moreau,

Need to create a stored procedure ,so cant touch the SSMS.
I am not saying to save using the SSMS table designer, just to use that tool to generate the script you need!
Avatar of Rias