Re: order is preserved by outer select?

From: Richard Huxton <dev(at)archonet(dot)com>
To: Joshua N Pritikin <jpritikin(at)pobox(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: order is preserved by outer select?
Date: 2007-07-13 08:45:19
Message-ID: 46973B9F.20301@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Joshua N Pritikin wrote:
> Here's another easy (stupid?) question:
>
> SELECT data.* FROM (SELECT * FROM foo ORDER BY bar) AS data
>
> Will the returned rows still be ordered by bar?

In practice, for this precise query, yes.

However, embedding this into a larger query or adding a WHERE clause
could re-order the results. For example, if PG uses a hash anywhere
during the query you'll lose ordering.

More importantly, the specifications say that without an ORDER BY the
order of a result-set is undefined. So if the developers find it's more
efficient to destroy order they are free to do so. That means you might
upgrade and have your application stop working.

So - good practice says don't rely on ORDER BY except in the outermost
level of your query.

--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Gregory Stark 2007-07-13 09:12:57 Re: One Large Table or Multiple DBs?
Previous Message Joshua N Pritikin 2007-07-13 08:36:10 order is preserved by outer select?