Answer the question
In order to leave comments, you need to log in
How to sort by list id in postgresql?
Hello. I'm trying to figure out how to sort a query like this:
select id, text from mytable where id in (5,13,2,1,6,10);
select id, text from mytable where id in (5,1,13,10) order by id=5 DESC, id=1 DESC, id=13 DESC, id=10 DESC;
Answer the question
In order to leave comments, you need to log in
select id, text from mytable where id in (5,13,2,1,6,10) order by idx(array[5,13,2,1,6,10], id);
select mt.id, mt.text from mytable as mt
join unnest('{5,13,2,1,6,10}'::int[]) with ordinality as t(id, ord) using (id)
order by t.ord;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question