3

If I have a query such as :

select * from tbl where id in (10, 20, 9, 4);

the results returned could potentially be in this order: 4, 9, 10, 20

but what if was looking to maintain the order of the list passed into the initial query? how would you approach this?

Ultimately I'm using Django as the ORM for my app here but I'm looking to investigate what is feasible at db level first.

Any ideas most welcome!

3 Answers 3

4

Using CASE isn't very portable because you have to know ahead of time all of the values and the order that you want to sort. The cleanest way is to use an array for the values and sort by the item's index in the array.

I had posted this to the Postgres Snippet Library a while back.

CREATE OR REPLACE FUNCTION idx(anyarray, anyelement)
  RETURNS int AS 
$$
  SELECT i FROM (
     SELECT generate_series(array_lower($1,1),array_upper($1,1))
  ) g(i)
  WHERE $1[i] = $2
  LIMIT 1;
$$ LANGUAGE sql IMMUTABLE;

SELECT * FROM foo ORDER BY idx(array['Freshman','Sophomore','Junior','Senior'], foo.grade_level)

0

You might then want to look at using a CASE in the ORDER BY statement

0

Take a look at this topic to see how you can create an array and use it to sort in a function. Works great!

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.