Search code examples
sql-serversql-server-2008select-query

How to sort month in a table when retrieving using the sql query?


I have a query which gets month name from a table. But this column isn't a datetime data type, It's a varchar column. How can I sort it according to the month name in ascending order?
This is the output I get at the moment.

August
November
October
September

This is my query

select distinct(payemnt_month) as month from payement_details

Solution

  • Use below one i have appended your month with day and year. Then i am extracting month number

    select * from payment_details order by DATEPART(MM,payemnt_month+'01'+'00')
    

    Update If possible update your query like below.

    SELECT * FROM 
    (
    SELECT DISTINCT month,
                    Datepart(MM, payemnt_month+ '01' + '00') MONTHNO
    FROM   payment_details )A
    ORDER  BY MONTHNO
    

    Or Like below if you don't have any issue to keep month no

       SELECT DISTINCT month,
                            Datepart(MM, payemnt_month+ '01' + '00') MONTHNO
            FROM   payment_details
    order by month,Datepart(MM, payemnt_month+ '01' + '00')