ActiveRecord Find All not sorting by ID?
Ordering by ID is not guaranteed by default. It’s up to the database how a non-ordered query gets ordered (typically it’s unspecified). If you want your results to be ordered, you need to specify an explicit order with order
, as you’ve done:
Model.order(id: :asc)
Note also that ordering by id
should only be done if you want a deterministic order. If you want to order by time, use created_at
or updated_at
(nothing guarantees that id
s are chronologically ordered). If you want all queries to always be ordered, you could use default_scope
, but generally its use should be avoided.
In SQL, tables are considered to be sets of records, not lists of records, and a 'select' query is not guaranteed to return records in any particular order unless an 'order by' clause is specifically included. You may happen to see that results come back in a particular order sometimes, but that doesn't mean you can or should assume it will always be so.
Using ActiveRecord, you can force a default 'order by' clause if you like by specifying a default scope. In general, that's a bad idea though, because it will force the server to do more work to give you a sorted result set, even when you don't need it sorted. Furthermore, sorting in the 'id' field is usually inappropriate, since the point of 'id' is to be an opaque record identifier with no purpose or meaning other than to be unique for a given record in a table.