Sorting data pulled from database ORDER BY

Hello,
Annotate-a-local-image
You have two columns as shown in the picture
1st column is Date 1, I want to sort from oldest to newest.
2nd column is Date 2, I want to sort new to oldest
Those whose Date 2 column is empty should appear as a group at the top
Non-blank fields in the Date 2 column should appear as a group at the end of the list.
So it’s not complicated
Note: Dates in columns like this “1635581546”
How to do this

You can start here.

SELECT column1, column2 FROM [table-name] 
ORDER BY 
[column-name1 ] [ASC|DESC] ,  
[column-name2] [ASC|DESC],..

ORDER BY date_2 ASC, date_1 ASC
With this query I get the following result


The blue area (date_1) is sorted as I want it (oldest to newest)
Red field (date_2), I want it to sort new to oldest

Here is the thing to consider.
The empty ones in the date_2 column should be at the top of the list. Date ones should be at the end of the list.

The problem here is I want to sort the red field from new to old

ORDER BY date_2 DESC, date_1 ASC when I set it like this the date_2 field goes to the top of the list

Can there be a condition in an ORDER BY?
Sample
ORDER BY date_2="" AND date_1 ASC, date_2!="" AND date_2 DESC as

There can be, but not exactly like that.

The following should work -

ORDER BY date_2, date_2 DESC, date_1

I did as in the example you gave but it didn’t work.

ORDER BY date_2, date_2 DESC, date_1

DESC or ASC doesn’t matter, it gives the same result as in the picture

The above looked right when I tried it. I must have been mistaken about what result you wanted.

Depending on what the empty values are (I’m using actual integer unix timestamps, with zeros for the empty values), this should work - ORDER BY date_2 = '' DESC, date_2 DESC, date_1

1 Like


Thank you very much
Now it’s exactly what I wanted
:+1: :+1: :+1: :+1:

Sponsor our Newsletter | Privacy Policy | Terms of Service