Thursday, May 21, 2015

Case in ORDER BY (or) Custom ORDER BY in SQL

Recently i have experienced with "Case in ORDER BY" in SQL Server.

Let's take a scenario:

I want  Week Names in Proper Order (MonDay to SaturDay) wile i am using ORDER BY Clause in sql.

While i gone for ORDER BY.. then i received DAY_NAME like this......
















To get the DAY_NAME properly we have to use case in ORDER BY....

select DAY_NAME from Dim_Date
order by 
case    WHEN DAY_NAME = 'Monday' THEN '1'
        WHEN DAY_NAME = 'Tuesday' THEN '2'
        WHEN DAY_NAME = 'Wednesday' THEN '3'
        WHEN DAY_NAME = 'Thursday' THEN '4'
        WHEN DAY_NAME = 'Friday' THEN '5'
        WHEN DAY_NAME = 'Saturday' THEN '6'
        WHEN DAY_NAME = 'Sunday' THEN '7'

ELSE DAY_NAME END ASC

OUTPUT:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

NOTE: It is very much useful, In case you have to show the Country List drop down. Here you want to show "INDIA " as First Name to be load in top.

No comments:

Post a Comment