Re: window function and order by

From: David Johnston <polobo(at)yahoo(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: window function and order by
Date: 2013-12-20 22:59:04
Message-ID: 1387580344957-5784292.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Torsten Förtsch wrote
> Hi,
>
> assuming I have a query that computes a running sum like this:
>
> select id, buy_price, sum(buy_price) over (order by id) sum
> from fmb
> where 202300<=id and id<=202400
> order by id;
>
> Do I need the ORDER BY clause at the end? Or does the ORDER BY in the
> window function already define the order of the result set?

It is possible for the final output to be out-of-order e.g. (2, 3, 1) but
the running total associated with each row will be correct. IOW, if you
were to manually perform an order-by on the result you would get the same
result as if you have included the outer (non-window) order-by in the
original query.

Input:
(1, 1), (2, 2), (3, 3)

Possible Output:
(2, 2, 3), (3, 3, 6), (1, 1, 1)

Expected Output:
(1,1,1), (2,2,3), (3,3,6)

Not Possible:
(2, 2, 2), (3,3,5),(1,1,6)

If you want the output in a specific order you should specify that order
explicitly. By coincidence, with simple queries, you may consistently get
the expected results but that is not something to rely upon.

David J.

--
View this message in context: http://postgresql.1045698.n5.nabble.com/window-function-and-order-by-tp5784285p5784292.html
Sent from the PostgreSQL - general mailing list archive at Nabble.com.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message AI Rumman 2013-12-20 23:19:52 Seems like bug in 9.1.3, need to confirm.
Previous Message Joseph Kregloh 2013-12-20 22:01:47 Re: pg_upgrade & tablespaces