CASE Statement in ORDER BY Clause


How you can you sort the table rows based on the column values based on the condition?

Means not ascending or descending order directly. what-if we want to order rows based on table column values based on our custom requirement.

To achieve the same, we can use CASE expression in an ORDER BY clause to determine the sort order of the rows based on a given column value.

Example :

SELECT * FROM Customers
ORDER BY case when country = ‘P’ then 1
when country = ‘A’ then 2
when country = ‘L’ then 3
when country = ‘H’ then 4
end asc

Hope this will help !!!

Jay Ganesh

Advertisements

One thought on “CASE Statement in ORDER BY Clause

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