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
From the comments:
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":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: