Sort Column names alphabetically in a table

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Sort Column names alphabetically in a table



In SQL Server, we get the table description using below command:


Sp_help TableName



When it displays all column names in a random order. Is there a way If I want to get all column names alphabetically sorted in some order (Descending or Ascending)?



This will help me to have a quick look at the table to see what all columns are present and whether a specific column is present in the table or not.





Possible duplicate of How do you return the column names of a table?
– Sam M
11 mins ago




3 Answers
3



You may get the List of Column from the System View INFORMATION_SCHEMA.COLUMNS. You can do a Select on the View and Filter by Table there order the List based on any of your desired values


INFORMATION_SCHEMA.COLUMNS


SELECT
*
FROM INFORMTION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='YourTableName'
ORDER BY COLUMN_NAME ASC





It's working. Thanks.
– Trupti J
7 mins ago



EDIT: Oops, other answer just beat me, and mine is in table order not alphabetical order. But look at Information_schema and you can do whatever you want.



Use information_schema.


select column_name from information_schema.columns where table_name='yourtable' order by ordinal_position





I wanted to sort alphabetically by column names, so I cannot sort by Ordinal_position.
– Trupti J
5 mins ago





Yep - I saw that hence my edit.
– TomC
47 secs ago



There is one more query to achieve this:


SELECT *
FROM sys.COLUMNS where object_id in (
select object_id from sys.OBJECTS where name = 'yourtablename')
order by NAME





instead of using the IN clause, you can Just use WHERE [Object_id] = OBJECT_ID('YourTableName')
– Jayasurya Satheesh
5 mins ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard