So I have 2 tables – Videos and Watches (with datetime). I want to order the videos by the last time watched by a given user, with the never before watched videos coming first and the rest being sorted by ascending order of the last watch.
What would be the query to do that?
An example of desired result:
Videos table has 5 videos with id 1, 2, 3, 4, 5
Views table has 3 entries, video 2 watched 2 hours ago, video 4 watched 5 days ago, video 5 watched just now
The return order should be [1, 3, 4, 2, 5]
2
Answers
You can use
NULLS FIRST
directive in `ORDER BYTest the query on fiddle
Result:
Do a left join of videos to views, collecting the max timestamp, and then do an ascending sort with nulls first on that column.
Setup: (next time please post a similar setup in your questions to save time)
Query: