From: | Evgeniy Shishkin <itparanoia(at)gmail(dot)com> |
---|---|
To: | Marti Raudsepp <marti(at)juffo(dot)org> |
Cc: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, David G Johnston <david(dot)g(dot)johnston(at)gmail(dot)com>, "pgsql-performance(at)postgresql(dot)org" <pgsql-performance(at)postgresql(dot)org> |
Subject: | Re: two table join with order by on both tables attributes |
Date: | 2014-08-08 13:57:37 |
Message-ID: | 7C443A2D-BD8A-4487-A424-F754411CB210@gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-performance |
> On 08 Aug 2014, at 16:29, Marti Raudsepp <marti(at)juffo(dot)org> wrote:
>
> On Fri, Aug 8, 2014 at 4:05 AM, Evgeniy Shishkin <itparanoia(at)gmail(dot)com> wrote:
>>>>>> select * from users join notifications on users.id=notifications.user_id ORDER BY users.priority desc ,notifications.priority desc limit 10;
>
>>>>> In my understanding, i need to have two indexes
>>>>> on users(priority desc, id)
>>>>> and notifications(user_id, priority desc)
>
>> And actually with this kind of query we really want the most wanted notifications, by the user.
>> So we really can rewrite to order by users.priority desc, id asc, notifications.priority desc according to business logic.
>
> You can rewrite it with LATERAL to trick the planner into sorting each
> user's notifications separately. This should give you the nestloop
> plan you expect:
>
> SELECT *
> FROM users,
> LATERAL (
> SELECT * FROM notifications WHERE notifications.user_id=users.id
> ORDER BY notifications.priority DESC
> ) AS notifications
> ORDER BY users.priority DESC, users.id
>
Thank you very much.
> It would be great if Postgres could do this transformation automatically.
>
> There's a "partial sort" patch in the current CommitFest, which would
> solve the problem partially (it could use the index on users, but the
> notifications sort would have to be done in memory still).
> https://commitfest.postgresql.org/action/patch_view?id=1368
>
> Regards,
> Marti
From | Date | Subject | |
---|---|---|---|
Next Message | Josh Berkus | 2014-08-08 19:15:36 | Optimization idea for long IN() lists |
Previous Message | Marti Raudsepp | 2014-08-08 13:29:39 | Re: two table join with order by on both tables attributes |