Re: ORDER BY results

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Howard Cole <howardnews(at)selestial(dot)com>
Cc: "'PgSql General'" <pgsql-general(at)postgresql(dot)org>
Subject: Re: ORDER BY results
Date: 2005-09-22 15:17:01
Message-ID: 20050922151701.GA96349@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Sep 22, 2005 at 02:19:00PM +0100, Howard Cole wrote:
> I have a query which presents results sorted using the SQL "ORDER BY...
> LIMIT". Now my question is... if the column that the order refers to
> has some repeated data, will the order of results always be the same?

Not necessarily -- if you want a certain order then you'll need a
more specific ORDER BY clause. Here's an example:

CREATE TABLE example (
id integer PRIMARY KEY,
stuff integer NOT NULL
);

INSERT INTO example (id, stuff) VALUES (1, 10);
INSERT INTO example (id, stuff) VALUES (2, 11);
INSERT INTO example (id, stuff) VALUES (3, 11);
INSERT INTO example (id, stuff) VALUES (4, 12);

SELECT id, stuff FROM example ORDER BY stuff;
id | stuff
----+-------
1 | 10
2 | 11
3 | 11
4 | 12
(4 rows)

UPDATE example SET stuff = 11 WHERE id = 2;

SELECT id, stuff FROM example ORDER BY stuff;
id | stuff
----+-------
1 | 10
3 | 11
2 | 11
4 | 12
(4 rows)

Notice that the second query returns rows in a different order than
the first query. In this simple example I'd guess that the order
is related to the tuples' physical locations on disk: when we updated
the row with id = 2 the database made another version of that row
and stored it in a later position (you can see tuples' physical
locations by selecting the ctid system column). If we ran VACUUM
and did the update again, the tuple would probably go back to its
original location (read up on MVCC to see how this works).

--
Michael Fuhr

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2005-09-22 15:26:55 Re: ORDER BY results
Previous Message Андрей 2005-09-22 15:16:17 Re: [Re] wrong protocol sequence?