4

I've just transitioned my app from MySQL to Postgres. Previously, a request for .all returned all the rows in id order. On Postgres the rows are returned out of order. Likewise,

Person.first

used to return the record with id 1, now it sometimes returns another record.

If I add an order clause like this:

Person.order("id").first

The query succeeds and returns the first row. Is this expected behaviour?

4
  • "Make me feel icky" to have a known ordering (removing a bug from your app) vs having random ordering (and keeping the bug)??? Commented Feb 7, 2013 at 18:45
  • MySQL orders by id by default. This is a sensible assumption. Commented Feb 8, 2013 at 10:50
  • I think it's InnoDB that orders by primary-key as a side-effect of its implementation. Other storage engines behave differently and I'm not sure Oracle issue any guarantees about ordering remaining the same in future. The SQL standards are pretty clear about result-set ordering being undefined unless you explicitly request one. Commented Feb 8, 2013 at 11:25
  • OK, fair enough. If I modify the question would you reverse the downvote? Commented Feb 8, 2013 at 13:09

1 Answer 1

4

this post answers your question:

I don't think ordering by ID is guaranteed by default, since I believe it's up to the database how a non-ordered query gets returned. You can make it be ordered so by defining a default scope at the top of your model like so:

default_scope order('id ASC')

Then calling Model.all will be equivalent to calling Model.order('id ASC').

Sign up to request clarification or add additional context in comments.

5 Comments

A default scope will override other scopes later in the query chain. It's not my preferred solution.
an alternative is to create a scope so you can use Person.by_id.first
I guess that's the way to go then. Thanks
If you choose to use this in Rail 4.2.0 (and perhaps earlier) you will need the scope to be in a block like so default_scope { order('id ASC') }.
@superluminary is there some web page about this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.