Reputation: 8121
Table users:
id | firstname | lastname
---+-----------+---------
1 | John | Smith
2 | Adam | Tensta
3 | Anna | Johansson
I want to select these in the order of ID 2, 3, 1. ONLY specified by the id-field. Is this possible?
I'm thinking something like SELECT * FROM users ORDER BY id ORDER(2,3,1)
Can this be done, and in that case how?
Upvotes: 13
Views: 15416
Reputation: 656471
For any number of values. Just pass an array of matching type with your preferred sort order:
SELECT u.*
FROM users u
LEFT JOIN unnest('{2,3,1}'::int[]) WITH ORDINALITY o(id, ord) USING (id)
ORDER BY o.ord;
This sorts rows without match last because ord
is NULL then and that sorts last in ascending order.
Similar solutions possible for older versions without ORDINALITY
.
Related:
SELECT * FROM users ORDER BY (id+1)%3
%
is the modulo operator.
Upvotes: 1
Reputation:
Should work with a CASE in the order by:
SELECT *
FROM users
ORDER BY case id when 2 then 1
when 3 then 2
when 1 then 3
end
Upvotes: 21