I know that the order of returned rows is not guaranteed with the IN
statement in Postgres. For example if I do this:
SELECT users.id FROM users WHERE users.id IN (13589, 16674, 13588)
I may get this result:
16674
13588
13589
However, I want returned rows to respect the order in the IN
list, so I found few solutions online, such as:
SELECT users.id FROM users WHERE users.id IN (13589, 16674, 13588)
ORDER BY POSITION(id::text in '(13589, 16674, 13588)')
or
SELECT users.id FROM users WHERE users.id IN (13589, 16674, 13588)
ORDER BY id = 13589 desc,
id = 16674 desc,
id = 13588 desc;
I wonder if there is a nicer way to do this, or better yet more efficient?
ORDER BY CASE WHEN ... THEN ...
as nicer ? As to efficiency, I'm pretty sure optimizer will generate the same plan.