public inbox for [email protected]  
help / color / mirror / Atom feed
From: Willow Chargin <[email protected]>
To: [email protected]
Cc: [email protected]
Subject: Re: Functionally dependent columns in SELECT DISTINCT
Date: Fri, 13 Sep 2024 08:26:53 -0700
Message-ID: <CAALRJs5QkE-yWVdxQxOLXbM8DyPVV3M_=zfsPK17SV-zHQsASQ@mail.gmail.com> (raw)
In-Reply-To: <[email protected]>
References: <CAALRJs5ne=gPYG=FdeY-G0p9QyjXHhPhAyAsJ_evdCwG3vuhug@mail.gmail.com>
	<[email protected]>

On Thu, Sep 12, 2024 at 11:13 PM <[email protected]> wrote:
>
> What about using DISTINCT ON () ?
>     SELECT DISTINCT ON (items.id) items.*
>     FROM items
>       JOIN parts ON items.id = parts.item_id
>     WHERE part_id % 3 = 0
>     ORDER BY items.id,items.create_time DESC
>     LIMIT 5;
>
> This gives me this plan: https://explain.depesz.com/s/QHr6 on 16.2  (Windows, i7-1260P)

Ordering by items.id changes the answer, though. In the example I gave,
items.id and items.create_time happened to be in the same order, but
that needn't hold. In reality I really do want the ID columns of the
*most recent* items.

You can see the difference if you build the test dataset a bit
differently:

    INSERT INTO items(id, create_time)
        SELECT i, now() - make_interval(secs => random() * 1e6)
        FROM generate_series(1, 1000000) s(i);

We want the returned create_times to be all recent, and the IDs now
should look roughly random.






view thread (3+ messages)  latest in thread

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected]
  Subject: Re: Functionally dependent columns in SELECT DISTINCT
  In-Reply-To: <CAALRJs5QkE-yWVdxQxOLXbM8DyPVV3M_=zfsPK17SV-zHQsASQ@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox