Re: Return rows in input array's order?

Поиск
Список
Период
Сортировка
От Steven Lembark
Тема Re: Return rows in input array's order?
Дата
Msg-id 20230509171104.583e6435.lembark@wrkhors.com
обсуждение исходный текст
Ответ на Re: Return rows in input array's order?  (Dominique Devienne <ddevienne@gmail.com>)
Список pgsql-general
On Tue, 9 May 2023 11:37:29 +0200
Dominique Devienne <ddevienne@gmail.com> wrote:

> On Tue, May 9, 2023 at 11:23 AM David Wheeler <hippysoyboy@gmail.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@wrkhors.com
+1 888 359 3508



В списке pgsql-general по дате отправления:

Предыдущее
От: Peter Eisentraut
Дата:
Сообщение: Re: ICU, locale and collation question
Следующее
От: Kirk Wolak
Дата:
Сообщение: Re: "PANIC: could not open critical system index 2662" - twice