Re: Why doesn't Postgres apply limit on groups when retrieving N results per group using WHERE IN + ORDER BY

From: Ron Johnson <ronljohnsonjr(at)gmail(dot)com>
To: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Why doesn't Postgres apply limit on groups when retrieving N results per group using WHERE IN + ORDER BY
Date: 2024-02-05 15:54:49
Message-ID: CANzqJaDC2MAVD9wsuCSNOPC+aFXWoWy8Ya0rnGNVJ454A-BYjA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Feb 5, 2024 at 7:23 AM Sean v <sean(at)vanmulligen(dot)ca> wrote:

> This is related to a question I asked on dbs.stackexchange.com:
> https://dba.stackexchange.com/questions/335501/why-doesnt-postgres-apply-limit-on-groups-when-retrieving-n-results-per-group
>
> But to reiterate - I have a query like this:
>
> SELECT "orders".*
>
> FROM "orders"
>
> WHERE (user_id IN ?, ?, ?)
>
> ORDER BY "orders"."created_at" LIMIT 50
>
[snip]

> So my question is twofold:
> - why doesn't Postgres use the composite index, and then retrieve only the
> minimum necessary amount of rows (50 per user) using the query I posted
> above?
>
>
But your query *does not* list the first 50 rows *per user*. It only
returns the first 50 rows of:

SELECT "orders".*

FROM "orders"

WHERE (user_id IN ?, ?, ?)

ORDER BY "orders"."created_at"

Who knows which users are going to be in that list???

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message David G. Johnston 2024-02-05 15:58:09 Re: Why doesn't Postgres apply limit on groups when retrieving N results per group using WHERE IN + ORDER BY
Previous Message arun chirappurath 2024-02-05 14:01:45 Unused indexes