Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering by the order of key value

Tags:

sql-server

The problem is: I have a table that i want sort items with special id.

For example:

Request(Id, Code, Phone, CreatedDate)

1  100  98351265  2014/2/2
2  101  98351269  2014/3/2 
3  102  98351985  2014/5/2 
4  103  98351654  2014/9/2

order by Id=3

result:

3  102  98351985  2014/5/2 
1  100  98351265  2014/2/2
2  101  98351269  2014/3/2 
4  103  98351654  2014/9/2

there is away to order by the order of key value.

like image 560
Niloo Avatar asked Jan 19 '26 05:01

Niloo


1 Answers

If you want to see records with Id = 3 first, and all other records being sorted by Id you can put it like that:

  select *
    from MyTable
order by case
           when Id = 3 then
             0
           else
             1
         end,    -- <- First, extract records with Id = 3
         Id desc -- <- Next, sort by Id
like image 50
Dmitry Bychenko Avatar answered Jan 20 '26 22:01

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!