ORDER BY the IN value list



  • 4 Answer(s)

    Do it quite simply includes (introduced in PostgreSQL 8.2) VALUES (), ().

    Below syntax:

    select c.*
    from comments c
    join (
      values
         (1,1),
         (3,2),
         (2,3),
         (4,4)
    ) as x (id, ordering) on c.id = x.id
    order by x.ordering
    
    Answered on January 7, 2019.
    Add Comment

    equitable because it is so problematic to find and it has to be spread: in mySQL this can be done much simpler, but I don’t know if it works in other SQL.

    SELECT * FROM `comments`
    
    WHERE `comments`.`id` IN ('12','5','3','17')
    
    ORDER BY FIELD(`comments`.`id`,'12','5','3','17')
    
    
    Answered on January 7, 2019.
    Add Comment

    It very simple ,it work for me

    SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
    
    ORDER BY id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC
    
    
    Answered on January 7, 2019.
    Add Comment

    Syntax will be like this:

    select c.*
    from comments c
    join (
      values
        (1,1),
        (3,2),
        (2,3),
        (4,4)
    ) as x (id, ordering) on c.id = x.id
    order by x.ordering
    Answered on March 5, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.