Here is my table
+------------+-----------+---------------+--------------+
| CommentId | ParentId | Timestamp | CommentText |
+------------+---------+-----------+--------------------+
| 1 | NULL | Jan 1 2:00pm | a |
| 2 | NULL | Jan 1 2:01pm | b |
| 3 | 1 | Jan 1 3:03pm | c |
| 4 | 2 | Jan 1 5:00pm | d |
| 5 | 2 | Jan 1 5:01pm | e |
| 6 | NULL | Jan 1 8:00pm | f |
| 7 | 1 | Jan 1 7:00pm | g |
| 8 | 6 | Jan 1 9:04pm | h |
| 9 | 1 | Jan 1 8:05pm | i |
| 10 | NULL | Jan 1 9:04pm | k |
+------------+-----------+---------------+--------------+
Currently I am using the following SQL to return the comments ordered by parent
SELECT c.*
FROM Comments c
ORDER BY COALESCE(c.ParentId, c.Id)
The result is this:
+------------+-----------+---------------+--------------+
| CommentId | ParentId | Timestamp | CommentText |
+------------+---------+-----------+--------------------+
| 1 | NULL | Jan 1 2:00pm | a |
| 3 | 1 | Jan 1 3:03pm | c |
| 7 | 1 | Jan 1 7:00pm | g |
| 9 | 1 | Jan 1 8:05pm | i |
| 2 | NULL | Jan 1 2:01pm | b |
| 4 | 2 | Jan 1 5:00pm | d |
| 5 | 2 | Jan 1 5:01pm | e |
| 6 | NULL | Jan 1 8:00pm | f |
| 8 | 6 | Jan 1 9:04pm | h |
| 10 | NULL | Jan 1 9:04pm | k |
+------------+-----------+---------------+--------------+
I need to get the results in a Descending timestamp order. The result set should look like:
+------------+-----------+---------------+--------------+
| CommentId | ParentId | Timestamp | CommentText |
+------------+---------+-----------+--------------------+
| 10 | NULL | Jan 1 9:04pm | k |
| 6 | NULL | Jan 1 8:00pm | f |
| 8 | 6 | Jan 1 9:04pm | h |
| 2 | NULL | Jan 1 2:01pm | b |
| 5 | 2 | Jan 1 5:01pm | e |
| 4 | 2 | Jan 1 5:00pm | d |
| 1 | NULL | Jan 1 2:00pm | a |
| 9 | 1 | Jan 1 8:05pm | i |
| 7 | 1 | Jan 1 7:00pm | g |
| 3 | 1 | Jan 1 3:03pm | c |
+------------+-----------+---------------+--------------+
The following does not work:
SELECT c.*
FROM Comments c
ORDER BY COALESCE(c.ParentId, c.Id), Timestamp DESC
I think that this query returns rows in the order that you want:
It orders rows in descending order by ParentID if it is not null, otherwise by ID, then rows with null go at the top, and then by timestamp desc.