Home > Net >  Multiple Ordering in Postgresql
Multiple Ordering in Postgresql

Time:03-31

I have two columns in a table (say Permissioned_on_Ques1, Permissioned_on_Ques2) of date type. I want to sort the table on latest updated date of both the columns. It should pick 1st column if both dates are equal.

Permissioned_on_Ques1     Permissioned_on_Ques2

31 Mar 2022 04:17:33      31 Mar 2022 04:17:33
30 Mar 2022 06:25:09      25 Feb 2022 03:35:43

CodePudding user response:

You can use greatest function to find the larger of the two dates and use it in order by:

order by greatest(Permissioned_on_Ques1, Permissioned_on_Ques2) desc

CodePudding user response:

Try:

SELECT
    Permissioned_onQues1,
    Permissioned_onQues2
FROM
    yourTableName
ORDER BY
    CASE WHEN Permissioned_onQues1 = Permissioned_onQues2
    THEN Permissioned_onQues1
    ELSE Permissioned_onQues2
    END
DESC

CodePudding user response:

If Permissioned_on_Ques1 and Permissioned_on_Ques2 are not-null columns:

  SELECT *
    FROM <table>
ORDER BY GREATEST ( Permissioned_on_Ques1
                  , Permissioned_on_Ques2
                  ) desc

And if columns can have null-values:

  SELECT *
    FROM <table>
ORDER BY CASE 
         WHEN Permissioned_on_Ques1 IS NOT NULL 
          and Permissioned_on_Ques2 IS NOT NULL
         THEN GREATEST
                     ( Permissioned_on_Ques1
                     , Permissioned_on_Ques2
                     )
         ELSE COALESCE
                   ( Permissioned_on_Ques1
                   , Permissioned_on_Ques2
                   )
              END desc
  • Related