Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql 11 - Order by integer array index

I want to list my products in the database according to their id order in the array

My array

'{3,2,1}'::int[]

For example

SELECT id FROM product WHERE id = ANY ('{3,2,1}'::int[]);

This query gets the products with ordered by product id

|id|
|1 |
|2 |
|3 |

But i want to list my products ordered by index of the array ids. Like this :

|id|
|3 |
|2 |
|1 |

Is it possible to do this ? How can i do ?

like image 977
Kerem Çakır Avatar asked Jul 26 '26 12:07

Kerem Çakır


2 Answers

You can use array_position():

ORDER BY array_position('{3,2,1}'::int[], id)

If you didn't want to repeat the array twice:

select p.id
from product p join
     (values ('{3,2,1}'::int[])) v(ar)
     on p.id = any(v.ar)
order by array_position(v.ar, p.id);
like image 198
Gordon Linoff Avatar answered Jul 29 '26 03:07

Gordon Linoff


You can unnest() the array with option WITH ORDINALITY to keep track of the index of each element, join it with the table and use the index as ORDER BY criteria:

SELECT p.id
FROM product AS p
INNER JOIN unnest('{3,2,1}'::int[]) WITH ORDINALITY AS a(id, nr) 
    ON p.id = a.id
ORDER BY a.nr;
like image 43
GMB Avatar answered Jul 29 '26 05:07

GMB