Avatar of RIAS
RIAS
Flag for United Kingdom of Great Britain and Northern Ireland asked on

How to rearrange column in a sql table by query

Hello,

How do I write a query to rearrange a column in table.
Microsoft SQL Server 2005Microsoft SQL ServerMicrosoft SQL Server 2008

Avatar of undefined
Last Comment
RIAS

8/22/2022 - Mon
Jim Horn

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.
Trideep Patel

Do you want to sort the output of the query based on some column(s)?

In such case you can use "order by"
Éric Moreau

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).
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
RIAS

ASKER
If not then is there any way i can insert a column in a table before another column ?
Trideep Patel

You can do it using the design view in SSMS (Sql Server Management Studio).
Éric Moreau

open the table designer in SSMS, select one of the column and click the INSERT key. That will insert a new column in between
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Trideep Patel

InsertColumn.jpg
RIAS

ASKER
need to have it in query ,please.
Cheers
ASKER CERTIFIED SOLUTION
Éric Moreau

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
RIAS

ASKER
Éric Moreau,

Need to create a stored procedure ,so cant touch the SSMS.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Éric Moreau

I am not saying to save using the SSMS table designer, just to use that tool to generate the script you need!
RIAS

ASKER
Cheers!