Home > Back-end >  SQL sorting by a column that is a String
SQL sorting by a column that is a String

Time:04-10

I am trying to write a query that will sort a column by the number that it is. However, the column is a string, so instead of sorting like 1, 2, 3, it will sort 1, 10, 11, 12, etc. Is there a way to change a column from a string to a number, or even a way to change how it orders the Strings. Here is my code and its output:

SELECT DISTINCT draft_number
    FROM NBA_data.dbo.all_seasons
        WHERE draft_year = '2016'
        ORDER BY draft_number;

Output:

draft_number
1
10
11
18
19
2
20
21

CodePudding user response:

Just cast draft_number to datatype INT in Order By clause.

ORDER BY CAST(draft_number As INT);

CodePudding user response:

Use ALTER TABLE to change the column type from string to number. Thus you don't have the hassle with every query on that column. Always use the appropriate data type for your data.

ALTER TABLE NBA_data.all_seasons ALTER COLUMN draft_number INT; 

Demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=23324061a0c49d61a0172d46ad74bb77

  • Related