From: | Steve Midgley <science(at)misuse(dot)org> |
---|---|
To: | "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com> |
Cc: | Shaozhong SHI <shishaozhong(at)gmail(dot)com>, Rob Sargent <robjsargent(at)gmail(dot)com>, pgsql-sql <pgsql-sql(at)lists(dot)postgresql(dot)org> |
Subject: | Re: How to just get the last in a recursive query |
Date: | 2022-04-05 00:00:00 |
Message-ID: | CAJexoS+0T96aLiXhp2duvJ+TGgu03ARa7Ld=mNR+VNsfuVTWtw@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On Mon, Apr 4, 2022 at 4:32 PM David G. Johnston <david(dot)g(dot)johnston(at)gmail(dot)com>
wrote:
> On Mon, Apr 4, 2022, 16:21 Shaozhong SHI <shishaozhong(at)gmail(dot)com> wrote:
>
>> That is not the most efficient in this case.
>
>
> Can you prove that statement? Provide a query that is more efficient.
>
Just to share the SQL from that example
WITH RECURSIVE walk_network(id, segment) AS (
SELECT id, segment
FROM network
WHERE id = 6
UNION ALL
SELECT n.id, n.segment
FROM network n, walk_network w
WHERE ST_DWithin(
ST_EndPoint(w.segment),
ST_StartPoint(n.segment),0.01))SELECT idFROM walk_network
David J (kind of off-topic): There's no *order by *in the original query,
so I could imagine that adding any order by clause at all would make the
query less efficient. But maybe it could become more efficient if the
planner picks a better index as a result?
David (OP): My main point is that in this example, since no order by clause
is provided, it is meaningless to talk about a "last" or "first" item. SQL,
afaik, is not required to produce the results in any order whatsoever, when
no order by clause is provided (corrections welcome if that's not
accurate). So while you might grab the last item somehow this time, it
might not be the last item, the next time you run the query. So I'd say you
should add an appropriate order by query, and then you can measure "ASC" vs
"DESC" with "LIMIT 1" to see if either one is less efficient. (I'm in David
J's camp that it's unlikely to make any difference)
Steve
From | Date | Subject | |
---|---|---|---|
Next Message | David G. Johnston | 2022-04-05 00:50:09 | Re: How to just get the last in a recursive query |
Previous Message | David G. Johnston | 2022-04-04 23:32:12 | Re: How to just get the last in a recursive query |