Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres keep order of array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can use unnest(...) WITH ORDINALITY and an INNER JOIN to retain the array index:

SELECT pages.id, pages.title
FROM pages
INNER JOIN unnest(ARRAY['6e3e4470', 'fec27534'])
               WITH ORDINALITY tbl(id, idx) ON pages.id=tbl.id
ORDER BY tbl.idx
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading