From: | Steven Lembark <lembark(at)wrkhors(dot)com> |
---|---|
To: | Dominique Devienne <ddevienne(at)gmail(dot)com> |
Cc: | David Wheeler <hippysoyboy(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org, lembark(at)wrkhors(dot)com |
Subject: | Re: Return rows in input array's order? |
Date: | 2023-05-09 21:11:04 |
Message-ID: | 20230509171104.583e6435.lembark@wrkhors.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Tue, 9 May 2023 11:37:29 +0200
Dominique Devienne <ddevienne(at)gmail(dot)com> wrote:
> On Tue, May 9, 2023 at 11:23 AM David Wheeler <hippysoyboy(at)gmail(dot)com>
> 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(at)wrkhors(dot)com
+1 888 359 3508
From | Date | Subject | |
---|---|---|---|
Next Message | Kirk Wolak | 2023-05-10 04:39:55 | Re: "PANIC: could not open critical system index 2662" - twice |
Previous Message | Peter Eisentraut | 2023-05-09 15:24:09 | Re: ICU, locale and collation question |