ORDER BY Clause with IF Statment

93 Views Asked by At

I am struggling with Order by clause with If statement without If statement it's working correctly. I have two keys points which is of int type and date which is of timestamp type in my test table. I am adding sample data for reference

Table Name - test

    id  points    date
    ------------------------
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    5   606       2019-12-9 09:01:10

So my query

SELECT id, points, date FROM test order by points desc

Returns

    id  points    date
    ------------------------
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10

This is the expected result but if I am trying to add points in If clause then it sort the points in alphabetic order

Query

SELECT id, points, date FROM test order by IF(TRUE, points, date) desc

Returns

    id  points    date
    ------------------------
    1   90        2019-12-14 09:01:10
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    2   10        2019-12-15 09:01:10

How can I achieve the result in numeric descending order.

Expected Result

    id  points    date
    ------------------------
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10

Note: I am using MYSQL 8.0.21

1

There are 1 best solutions below

0
GMB On BEST ANSWER

From the comments:

I want to sort my result on the basis of user input, user can choose, he want to sort the result by points or date field

The two columns have different datataypes, so you would need two different levels of sorting. Assuming that user input is given as parameter :order_col, that may take value "points" or "date":

order by 
    case when :order_col = 'points' then points end desc,
    case when :order_col = 'date' then date end desc

An alternative would be to turn the date to a number, for example using unix_timestamp(): the datatypes are then consistent, and a single level of sorting is sufficient:

order by case :order_col
    when 'points' then points
    when 'date' then unix_timestamp(date)
end desc