Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN construct in the WHERE clause:

SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));

This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4.

I want the resulting rows sorted like the list in the IN construct: (1,3,2,4).

How to achieve that?

1 Answer

0 votes
by (40.7k points)

It'll be quite easy to do with VALUES (), () which is introduced in PostgreSQL 8.2.

Use the below query:

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

Related questions

0 votes
1 answer
0 votes
3 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in SQL by Tech4ever (20.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...