user2554301
user2554301

Reputation: 7

How to order your result in a specific way in SQL Server

I have a simple query, but I would like to see the results in a specific way. I would like to see 'N/A' at the top of the result, without having to result to "Case When Then"

Select  *
From Ordertype

Results:

Car21
Car34
Bus42
N/A

Thanks,

Upvotes: 0

Views: 90

Answers (3)

Brad
Brad

Reputation: 12245

If you want an arbitrary order that is not tied directly to the structured of a column (alphabetical/numerical) but rather to it's importance which only you know in your head it can be useful to add a Rank column to your table.

Column1 Rank
Car21   
Car34   2
Bus42   1
N/A     99

then you can do

select Column1 
from Table 
order by rank desc, column1

This will put highly ranked items first then low ranked items, then when rows don't have a rank it will sort them alphabetically by column1

Upvotes: 1

bhamby
bhamby

Reputation: 15450

There are no 'overrides' for ORDER BY, if you want the specific order you're asking for, you'll have to use the CASE:

SELECT type
FROM OrderType
ORDER BY 
 CASE
    WHEN type = 'N/A' THEN 1
    ELSE 2
 END 
,type

Upvotes: 2

Sami Khoury
Sami Khoury

Reputation: 28

You can try this:

SELECT * FROM ordertype ORDER BY ID DESC 

to see the newest ones 1st

Upvotes: 0

Related Questions