Joe
Joe

Reputation: 399

Confusion in order by clause in SQL server

I want to use order by clause to return 'id' column value of my table in sorted order like '1,2,3,4..' but the the following query returning value of id in the order '1, 10, 100, 101, 102...'

select id from loginuser order by id;

May I know can I get my desirable output?

Upvotes: 0

Views: 796

Answers (3)

onedaywhen
onedaywhen

Reputation: 57023

Adding to @Greco's answer, it is good practise to expose the sort order to the caller. Anyhow, using an expression in the ORDER BY clause violates SQL Standards. Therefore, consider this alternative:

SELECT id, CAST(id AS INTEGER) AS sort_col  
  FROM loginuser 
 ORDER 
    BY sort_col;

Upvotes: 0

bw_üezi
bw_üezi

Reputation: 4564

if possible you should change the column type in your database.

Upvotes: 2

Dimi Takis
Dimi Takis

Reputation: 4949

Your id column is of type varchar, try casting to int in the order by clause to get the desired result.

Upvotes: 7

Related Questions