Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does update change the order of records in a table in PostgreSQL?

My code depends on the order of records in the table. My assumption was that a table can be considered a list so that the records maintain order. I have a small update code as shown below that will update a record at a particular index in the table.

p = pieces[index]

p.position = 0

p.save

I check the order of records before this update and after this update then i see that after the update the record that is updated is moved to the last of the list. I print Piece.all to print the list. The order is maintained in mysql but when i deploy it to heroku which uses postgre the order was not maintained so this was a surprising find for me.

Is there no guarantee of order in tables and one should not depend on the order? Please correct my misunderstanding and thanks for the clarification.

like image 367
kofhearts Avatar asked Dec 14 '22 02:12

kofhearts


2 Answers

You should NEVER depend on the order in my honest opinion.

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.

MySQL tends to return rows in the order they're inserted, and this is why you see the different in behavior.

If you want them to always be returned in the order they were created, you can use Item.order("created_at")

like image 177
grepsedawk Avatar answered Dec 30 '22 10:12

grepsedawk


You state:

My assumption was that a table can be considered a list so that the records maintain order.

This is incorrect. A table represents an unordered set. There is no inherent ordering in the table. A result set similarly lacks ordering. The only way to guarantee the ordering of a result set is to use ORDER BY in the query.

So, an update changes values in one or more columns in one or more rows. It does not change the "ordering" of rows, because they are not ordered.

Note: Under some circumstances, a query may appear to return results in a particular order. You really should not depend on this behavior, unless the query has an explicit ORDER BY.

like image 33
Gordon Linoff Avatar answered Dec 30 '22 09:12

Gordon Linoff