1

I'm trying to sort two date columns in the table, FinalReviewDate, and DateDelivered. Any column with a DateDelivered is always going to have a FinalReviewDate that preceeds it, but a project can have a FinalReviewDate without having a DateDelivered. I used ASC to ORDER BY for both columns and received this result.

Final Review Date    Date Delivered
NULL                   NULL
NULL                   NULL
xxxx-xx-xx            xxxx-xx-xx
xxxx-xx-xx             NULL


How can I ORDER BY so my result looks like this instead?

Final Review Date    Date Delivered
NULL                   NULL
NULL                   NULL
xxxx-xx-xx             NULL
xxxx-xx-xx             xxxx-xx-xx

I don't know how to factor in the NULL values so they're included when I ORDER BY both tables. Here's the code I'm using.

$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate, DateDelivered FROM Projects
              WHERE DateAccepted IS NULL
              ORDER BY FinalReviewDate ASC, DateDelivered ASC";
$result = $conn->query($sql);
Tony
  • 298
  • 3
  • 17

1 Answers1

0

You can add two conditions into begin of ORDER BY section: FinalReviewDate IS NULL DESC, DateDelivered IS NULL DESC:

$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate, DateDelivered 
    FROM Projects
    WHERE DateAccepted IS NULL
    ORDER BY FinalReviewDate IS NULL DESC, DateDelivered IS NULL DESC, 
        FinalReviewDate ASC, DateDelivered ASC";
$result = $conn->query($sql);
Nick
  • 9,735
  • 7
  • 59
  • 89
  • That worked beautifully. So, I take it the first two IS NULL DESC sorted the null values first? – Tony Nov 29 '15 at 17:56
  • Yes, `FinalReviewDate IS NULL` return TRUE if field is null. If we want to see these lines at start, we are sorting them in descending order: firsts FALSE, after - TRUE – Nick Nov 29 '15 at 18:03
  • I didn't know I could sort those first. I found several examples on here and tried them, but they didn't work for me. I appreciate the help. – Tony Nov 29 '15 at 18:23