Re: Clustered table order is not preserved on insert

From: Richard Huxton <dev(at)archonet(dot)com>
To: Andrus <eetasoft(at)online(dot)ee>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Clustered table order is not preserved on insert
Date: 2006-04-26 19:11:40
Message-ID: 444FC5EC.9060908@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Andrus wrote:
> I have table of reports
>
> CREATE TABLE report (
> ReportName CHAR(5) not null check (reportname<>''),
> < a lot of other fields >,
> id serial primary key
> )
>
> I want to duplicate report so that id order is preserved.

Tables aren't ordered by definition. If you want to get results back in
a particular order use ORDER BY, possibly wrapped in a view.

> BEGIN;
> CREATE temp TABLE tempreport AS
> SELECT * FROM report
> WHERE reportname='oldr'
> ORDER BY id;
>
> ALTER TABLE tempreport DROP COLUMN id;
> update tempreport set reportname='newr';
> insert into report SELECT * FROM tempreport;
> DROP TABLE tempreport;
> COMMIT;
>
> SELECT *
> FROM report
> WHERE reportname='newr'
> ORDER BY id;
>
> Observed:
>
> order of some rows in newr is different than in oldr

Yes

> Expected:
>
> newr must have exactly the same order since
> CREATE temp TABLE tempreport AS .... ORDER BY id
> creates clustered table.

And the INSERT INTO ... SELECT didn't ask for any order.

If you really want to do this, then try something like

-- Don't drop the id column
UPDATE tempreport SET ...;
INSERT INTO report SELECT reportname,... FROM tempreport ORDER BY id;
DROP TABLE tempreport;

> Is this best method to preform this?
> Why postgres 8.1.3 changes order ?

There is no order inside a table - you must supply your own.

Although the solution I describe should work it's still not a good idea.
The reason you are having this problem is that you are trying to do two
things with one column. You are using "id" as a unique ID number and
also as a sort order. If you have a separate sort_order this will let
you duplicate reports as you desire and also allow you to re-arrange
reports without changing their IDs.

Can I recommend getting a book or two on relational theory - "An
Introduction to Database Systems" by Date is widely available.
--
Richard Huxton
Archonet Ltd

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Holger Zwingmann 2006-04-26 19:33:32 Moving a data base between differnt OS
Previous Message Douglas McNaught 2006-04-26 19:00:44 Re: Clustered table order is not preserved on insert