Order by datetime column desc

sudhir bharti 1 Reputation point
2021-01-26T05:40:10.45+00:00

I have a column with following values:

ToFromDateTimeSS
01/25 10:31:25 AM
01/25 10:31:23 AM
01/25 9:58:24 AM
01/25 9:58:22 AM
01/25 9:57:14 AM
01/25 9:57:12 AM
01/25 9:57:10 AM
01/25 9:57:08 AM
01/25 9:55:29 AM
01/25 9:55:27 AM
01/25 9:26:24 PM
01/25 9:26:22 PM
01/25 9:00:51 AM
01/25 9:00:49 AM
01/25 8:54:57 AM
01/25 8:54:57 AM
01/25 7:48:12 PM
01/25 7:48:10 PM
01/24 8:30:57 PM
01/24 8:30:57 PM
01/24 8:20:40 PM
01/24 8:20:40 PM

I want to sort the column order by ToFromDateTimeSS desc.

Note: the column is varchar datatype.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,601 questions
{count} votes

1 answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,581 Reputation points
    2021-01-26T07:50:05.623+00:00

    Hi @sudhir bharti ,

    Welcome to the Microsoft TSQL Q&A Forum!

    The date format you provided is not the SQL Server standard date format.Can the format of the inserted date be changed?

    If it can be changed,please refer to:

    create table #test (ToFromDateTimeSS varchar(25))  
    insert into #test values('01/25/2021 10:31:25 AM'),('01/25/2021 9:58:24 AM'),('01/25/2021 9:58:22 AM')  
    ,('01/25/2021 9:57:14 AM'),('01/25/2021 9:57:12 AM')  
      
    select * from #test  
    order by convert(datetime,ToFromDateTimeSS) desc  
    

    Output:
    60539-image.png

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments