I’ve got a simple array of IDs and need the query to reply with the same order
the query
SELECT id, title FROM pages WHERE id = ANY(ARRAY['6e3e4470', 'fec27534'])
the result
id title
fec27534 2020
6e3e4470 2022
as you can see the array provides the "2022" ID first, but the response replies with it the last result
is there a way to keep this ordered by the array provided?
Thanks in advance
2
Answers
You can use
unnest(...) WITH ORDINALITY
and anINNER JOIN
to retain the array index:Since you would not know whether all ids will be found, the ordering is probably not super useful, you should probably check it on the client against the input anyway.
You can however do it in Postgres as well:
(online demo)
If you do want to get back only the found rows, use an inner
JOIN
instead of theLEFT JOIN
.