Results 1 to 6 of 6
  1. #1
    Join Date
    Sep 2008
    Posts
    4

    Unanswered: how to order by bigger of 2 columns (solved)

    I have a simple table

    posts(text, created_at, commented_at)

    Is it possible to find all posts and order them by the larger value of created_at or commented_at? Something like
    Code:
    "select * from posts order by max(created_at, commented_at)"
    Last edited by sthapit; 08-13-09 at 09:43. Reason: solved

  2. #2
    Join Date
    Nov 2003
    Posts
    2,935
    Provided Answers: 12
    Try this:
    Code:
    SELECT * 
    FROM posts 
    ORDER BY CASE 
               WHEN created_at > commented_at THEN created_at
               ELSE commented_at
             END
    You might want to make sure it's working properly if any of the two dates can be NULL

  3. #3
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    try this:
    Code:
    ...ORDER BY GREATEST( created_at , commented_at )
    no need to check for NULL, the function takes care of that

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  4. #4
    Join Date
    Nov 2003
    Posts
    2,935
    Provided Answers: 12
    Quote Originally Posted by r937
    ORDER BY GREATEST
    no need to check for NULL, the function takes care of that
    I always forget about the non-standard functions

  5. #5
    Join Date
    Sep 2008
    Posts
    4
    that works perfectly thanks!

    out of curiosity, is there a similar function to greatest for mysql?

  6. #6
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Quote Originally Posted by sthapit
    out of curiosity, is there a similar function to greatest for mysql?
    yes, there is
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •