Custom sort order in a SQL statement

I tracked a status of a record in a text field and wanted to sort the results in a specific order. For example I want “active” to show before “rejected” and “deleted” to show up last, etc… It turns out it was pretty easy to do in SQL. Here it is:

select * from viewoffers where itemid=@ItemId

order by

    case status

    when ‘active’ then 1

    when ‘rejected’ then 2

    else 99

end

Advertisements

0 thoughts on “Custom sort order in a SQL statement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s