What you observe is most probably the result of a query without ORDER BY
, in which case rows are returned in arbitrary order. Postgres typically (but not necessarily) retrieves rows in physical order in this case.
Contrary to what @Haleemur commented an UPDATE
is in fact very similar to a DELETE
and INSERT
in PostgreSQL's MVCC model. A new row version is written for every update. Only large columns that are stored out-of-line ("TOASTed") are not rewritten unless these columns are updated.
So, if you don't ORDER BY
(which you probably should), rows are typically moved to the end of the table when updated (according to their physical location), but that can be changed any time and without warning, for instance by another UPDATE
or by VACUUM
. Never rely on the physical location.
I want all rows in the same order like they where created, no matter
how often they are updated.
So add a serial
column to the table and order by it:
CREATE TABLE foo (foo_id serial PRIMARY KEY, foo text);
SELECT * FROM foo ORDER BY foo_id;