Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres default sort by id - worldship

I need to setup worldship to pull from one of our postgres databases. I need to have it so that the packages are sorted by id. I have no way (that i am aware of) of having worldship send the order by clause so I need to have the default for the records returned to be returned by id.

On a second note I have no idea how postgres default sorts it looks like it by the last time the record was changed so if i write a two records id 1,2 then change record 2 when I run the query it returns them with record 2 being first.

like image 641
Ominus Avatar asked Jul 05 '11 16:07

Ominus


3 Answers

Rows are returned in an unspecified order, per sql specs, unless you add an order by clause. In Postgres, that means you'll get rows in, basically, the order that live rows read on the disk.

If you want a consistent order without needing to add an order by clause, create a view as suggested in Jack's comment.

like image 114
Denis de Bernardy Avatar answered Oct 01 '22 18:10

Denis de Bernardy


There is no such thing as a "default sort". Rows in a table are not sorted.

You could fake this with a view (as suggested by Jack Maney) there is no way you can influence the order of the rows that are returned.

But if you do that, be aware that adding an additional ORDER BY to a SELECT based on that view will sort the data twice.

Another option might be to run the CLUSTER command on that table to physically order the rows on the disk according to the column you want. But this sill does not guarantee that the rows are returned in that order. Not even with a plain SELECT * FROM your_table (but chances are reasonably high for that). You will need to re-run this statement on a regular basis because the order created by the CLUSTER command is not automatically maintained.

like image 39
a_horse_with_no_name Avatar answered Oct 01 '22 18:10

a_horse_with_no_name


For what it's worth, which probably isn't much, PostgreSQL's "default" ordering is based on the time the records were last updated. The most recently updated records will appear last.

like image 27
Webucator Avatar answered Oct 01 '22 17:10

Webucator