On Tue, 9 May 2023 11:37:29 +0200 Dominique Devienne <ddevienne@xxxxxxxxx> wrote: > On Tue, May 9, 2023 at 11:23 AM David Wheeler <hippysoyboy@xxxxxxxxx> > wrote: > > > > Hi. With an integer identity primary key table, > > > we fetch a number of rows with WHERE id = ANY($1), > > > with $1 an int[] array. The API using that query must return > > > rows in the input int[] array order, and uses a client-side > > > mapping to achieve that currently. > > > > > > Is it possible to maintain $1's order directly in SQL? > > > Efficiently? > > > > We’ve done this before with an “order by array_index(id, > > input_array)”. I forget the actual function consider that pseudo > > code > > Thanks David. I see how this would work. > > It was only used for small arrays but never noticed any performance > issues > Depending on your PG version: Create a temp table via unnest, join that with what you need and order by tmp.seq. Forgot which version allows inlining of CTE's but you can use a CTE (12?): with int_seq as ( select unnest( int_array_col ) "order_by" from whatever where blah ) select <whatever> from foobar a join int_seq b on a.foo = b.order_by order by b.order_by , <whatever else> This dodges the tmp table and the optimizer can inline the results, probably gets you the fastest result. -- Steven Lembark Workhorse Computing lembark@xxxxxxxxxxx +1 888 359 3508