Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Column names alphabetically in a table

Tags:

sql-server

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.

like image 486
Trupti J Avatar asked Jan 02 '23 22:01

Trupti J


2 Answers

You may get the List of Column from the System View which is 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 as mentioned below:

SELECT  
    *
    FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME ='YourTableName'
        ORDER BY COLUMN_NAME ASC
like image 182
Jayasurya Satheesh Avatar answered Jan 04 '23 13:01

Jayasurya Satheesh


There is one more query to achieve this:

SELECT  * 
        FROM    sys.COLUMNS where object_id = OBJECT_ID('yourtablename') 
        ORDER   By NAME
like image 31
Trupti J Avatar answered Jan 04 '23 11:01

Trupti J