Re: Window function order changing order of whole query

From: Martijn van Oosterhout <kleptog(at)svana(dot)org>
To: Thom Brown <thombrown(at)gmail(dot)com>
Cc: PGSQL Mailing List <pgsql-general(at)postgresql(dot)org>
Subject: Re: Window function order changing order of whole query
Date: 2009-10-12 08:31:56
Message-ID: 20091012083155.GE22604@svana.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Oct 12, 2009 at 09:13:09AM +0100, Thom Brown wrote:
> I tried posting this on the pgsql-sql but they don't seem to be posting
> successfully there, so I'm re-posting it here.
>
> I've had a look at examples of lag and lead window functions with order by
> inside the OVER clause, and I'm confused as to why it influences the overall
> order in the output.

Given that you didn't specify an order for the outer query, postgres is
allowed to give you the rows in any order it likes. In this case that
happens to be the order you see. If you would like another order you
need to specify it.

> For example (for a table called category with incrementing id numbers up to
> 26):
>
> SELECT id, lag(id) OVER (ORDER BY id DESC) FROM category;
>
> This would yield:
>
> id lag
> 26 NULL
> 25 26
> 24 25
>
> This is the equivalent of what we would get with:
> SELECT id, lead(id) OVER (ORDER BY id ASC) FROM category ORDER BY id DESC;

Have a nice day,
--
Martijn van Oosterhout <kleptog(at)svana(dot)org> http://svana.org/kleptog/
> Please line up in a tree and maintain the heap invariant while
> boarding. Thank you for flying nlogn airlines.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message peixubin 2009-10-12 09:25:39 Re: table full scan or index full scan?
Previous Message Thom Brown 2009-10-12 08:13:09 Window function order changing order of whole query